Best JavaScript code snippet using mountebank
SendMessageScreen.js
Source:SendMessageScreen.js  
1import React from 'react';2import { StyleSheet, Text, View,ScrollView,Dimensions,StatusBar,KeyboardAvoidingView,TouchableOpacity,Platform} from 'react-native';3import {Button,Item,Input,ListItem, List } from 'native-base'4import * as firebase from 'firebase'5import {FontAwesome,Ionicons} from '@expo/vector-icons'6import dateformat from 'dateformat'7import Animated from 'react-native-reanimated'8const HEADER_HEIGHT = Platform.OS == 'ios' ? 115 : 70+StatusBar.currentHeight9import { Avatar } from 'react-native-elements';10import * as Font from 'expo-font'11import GestureRecognizer, {swipeDirections} from 'react-native-swipe-gestures';12const {width,height} = Dimensions.get("screen")13import STYLES from '../../styles/styles'14import config from "../config"15export class SendMessageScreen extends React.Component {16  constructor(props){17    super(props);18    this.ref = React.createRef();19    this.scrollY = new Animated.Value(0)20    this.diffClampScrollY = Animated.diffClamp(this.scrollY,0,HEADER_HEIGHT)21    this.headerY = Animated.interpolate(this.diffClampScrollY,{22      inputRange : [0, HEADER_HEIGHT],23      outputRange : [0,-HEADER_HEIGHT]24    })25    this.state = {26        user : null,userId : null,foundUser : null,foundUserId : null,objectIdUser : null,objectIdOther : null,27        messages : [],message : "",waiting : true,fontLoaded : false28    }29  }30  componentDidMount(){31      firebase.auth().onAuthStateChanged(authenticate => {32        if(authenticate){33            const toSeeUser = this.props.route.params.params.uid34            if(!toSeeUser){35                this.props.navigation.goBack()36            }37            this.setState({ userId : authenticate.uid, foundUserId : toSeeUser,today : this.todayDate()})38            this.findUser(authenticate.uid)39            this.findOtherUser(toSeeUser)40            this.findMessages()41            this.loadFonts()42        }else{43            this.props.navigation.replace("Signin")44        }45      })46  }47  loadFonts = async() => {48    await Font.loadAsync({49      'Satisfy' : require("../../../assets/fonts/Satisfy-Regular.ttf"),50      'Caveat' : require("../../../assets/fonts/Caveat-Regular.ttf"),51    })52    this.setState({ fontLoaded : true })53  }54  findUser = async uid => {55    var users = firebase.database().ref("Users")56    await users.on("value",data => {57      if(data.val()){58        var keys = []59        var index = 0;var matchedIndex;60        data.forEach( D => {61          keys[index] = D.key62          index++;63        } )64        index = 0;65        var Users = Object.values(data.val())66        var matchedUser = Users.filter(u => {67          if(uid === u.uid){68            matchedIndex = index69          }70          index++;71          return uid === u.uid72        })73        if(matchedUser.length == 1){74          this.setState({ user : matchedUser[0],objectIdUser : keys[matchedIndex]})75        }76      }else{77        this.props.navigation.replace("Signup")78      }79    })80  }81  findOtherUser = userId => {82    var users = firebase.database().ref("Users")83    users.on("value",data => {84      if(data.val()){85        var keys = []86        var index = 0;var matchedIndex;87        data.forEach( D => {88          keys[index] = D.key89          index++;90        } )91        index = 0;92        var Users = Object.values(data.val())93        var matchedUser = Users.filter(u => {94          if(userId === u.uid){95            matchedIndex = index96          }97          index++;98          return userId === u.uid99        })100        if(matchedUser.length == 1){101          this.setState({ foundUser : matchedUser[0],objectIdOther : keys[matchedIndex] })102        }103      }else{104        this.props.navigation.replace("Signup")105      }106    })107  }108  findMessages = () => {109    var messages = this.state.user.messages110    if(messages == undefined){111      this.setState({ messages : [] })112    }else{113      var msgsWithOtherUser = messages.filter(withEach => {114        return withEach.otherUserUid === this.state.foundUser.uid115      })116      if(msgsWithOtherUser.length == 1){117        var msgs = msgsWithOtherUser[0].Messages118        msgs.sort(function(a, b) { 119           return new Date(a.timestamp) - new Date(b.timestamp);  120        });121        this.setState({ messages : msgs, waiting : false })122      }123    }124  }125  returnTime = () => {126    var now = new Date();127    var Dates = dateformat(now, 'mmm d yyyy h:MM:ss TT');128    var time = dateformat(now, 'h:MM TT')129    return {130      time : time, date : Dates131    }132  }133  append = message => {134    var currentUser = firebase.database().ref("Users/" + this.state.objectIdUser )135    var otherUser = firebase.database().ref("Users/" + this.state.objectIdOther )136    137    const data = this.returnTime()138    var newMessage = {139      text : message,140      timestamp : data.time,141      user : { _id : this.state.user.uid },142      date : data.date,143      _id : this.state.user.uid144    }145    var currentMessages,messageList;146    currentUser.on("value",DATA => {147      if(DATA.val()){148        currentMessages = DATA.val().messages149        var index = 0 ; var matchedIndex;150        var msgsWithOther = currentMessages.filter(withEach => {151          if(withEach.otherUserUid == this.state.foundUser.uid){152            matchedIndex = index153          }154          index++155          return withEach.otherUserUid == this.state.foundUser.uid 156        })157        if(msgsWithOther.length == 0){158          currentMessages.push({159            otherUserUid : this.state.foundUser.uid ,160            Messages : [newMessage]161          })162        }else{163          currentMessages[matchedIndex].Messages.push(newMessage)164        }165        messageList = DATA.val().messageList166        var newEntryInML = {167          userUid : this.state.foundUser.uid,168          objectId : this.state.objectIdOther,169          userProfile : this.state.foundUser.userProfile,170          userName : this.state.foundUser.userName,171          name : this.state.foundUser.name,172          lastMsgText : message,173          time : data.time,174          date : data.date175        }176        if(messageList == undefined){177          messageList = [newEntryInML]178        }else{179          index = 0;180          var otherUserInML = messageList.filter( eachEntry => {181            if(eachEntry.userUid == this.state.foundUser.uid ){182              matchedIndex = index183            }184            index++;185            return eachEntry.userUid == this.state.foundUser.uid186          } )187          if(otherUserInML.length == 0){188            messageList.unshift(newEntryInML)189          }else{190            191            var newList = messageList.slice(0,matchedIndex)192            newList = newList.concat(messageList.slice(matchedIndex + 1, messageList.length ))193            messageList = newList194            messageList.unshift(newEntryInML)195          }196        }197      }198    })199    var currentMessages2,messageList2;200    otherUser.on("value",DATA => {201      if(DATA.val()){202        currentMessages2 = DATA.val().messages203        var index = 0 ; var matchedIndex;204        var msgsWithOther2 = currentMessages2.filter(withEach => {205          if(withEach.otherUserUid == this.state.user.uid){206            matchedIndex = index207          }208          index++209          return withEach.otherUserUid == this.state.user.uid 210        })211        if(msgsWithOther2.length == 0){212          currentMessages2.push({213            otherUserUid : this.state.user.uid ,214            Messages : [newMessage]215          })216        }else{217          currentMessages2[matchedIndex].Messages.push(newMessage)218        }219        index = 0;220        messageList2 = DATA.val().messageList221        var newEntryInML = {222          userUid : this.state.user.uid,223          objectId : this.state.objectIdUser,224          userProfile : this.state.user.userProfile,225          userName : this.state.user.userName,226          name : this.state.user.name,227          lastMsgText : message,228          time : data.time,229          date : data.date230        }231        if(messageList2 == undefined){232          messageList2 = [newEntryInML]233        }else{234          index = 0;235          var currentUserInML = messageList2.filter( eachEntry => {236            if(eachEntry.userUid == this.state.user.uid ){237              matchedIndex = index238            }239            index++;240            return eachEntry.userUid == this.state.user.uid241          } )242          if(currentUserInML.length == 0){243            messageList2.unshift(newEntryInML)244          }else{245            var newList = messageList2.slice(0,matchedIndex)246            newList = newList.concat(messageList2.slice(matchedIndex + 1, messageList2.length ))247            messageList2 = newList248            messageList2.unshift(newEntryInML)249          }250        }251      }252    })253    currentUser.update({254      messages : currentMessages,messageList : messageList255    })256    .then(()=> {  this.setState({ message : "" })  })257    .catch(err => {alert(err.message)})258    otherUser.update({259      messages : currentMessages2,messageList : messageList2260    })261    .then(()=>{this.findMessages()})262    .catch(err => {alert(err.message)})263  }264  todayDate = () => {265    var now = new Date();266    return dateformat(now,'mmm d yyyy')267  }268  sendToMsgScreen = () => {269    this.props.navigation.push("Message",{270      params : { objectId : this.state.objectIdUser }271    })272  }273 274  onSwipe(gestureName, gestureState) {275    const {SWIPE_UP, SWIPE_DOWN, SWIPE_LEFT, SWIPE_RIGHT} = swipeDirections;276    this.setState({gestureName: gestureName});277    switch (gestureName) {278      case SWIPE_UP:279        // this.setState({backgroundColor: 'red'});280        break;281      case SWIPE_DOWN:282        // this.setState({backgroundColor: 'green'});283        break;284      case SWIPE_LEFT:285        // this.setState({backgroundColor: 'blue'});286        break;287      case SWIPE_RIGHT:288        // this.setState({backgroundColor: 'yellow'});289        this.sendToMsgScreen()290        break;291    }292  }293 294  render(){295    if( this.state.waiting || !this.state.fontLoaded ){296      return(  297        <Text style={{color : "white"}}> Waiting </Text>298      )299     }else{300        return (301          <KeyboardAvoidingView  behavior="position" style={[{flex: 1},STYLES.generalPage]}  >302            <GestureRecognizer303              onSwipe={(direction, state) => this.onSwipe(direction, state)}304              config={config}305              style={{306                flex: 1,307              }}308            >309               <Animated.View style={{310                    position : "absolute",311                    left : 0,312                    right : 0,313                    top : 0,314                    height : HEADER_HEIGHT-StatusBar.currentHeight,315                    backgroundColor : '#362c2b',316                    width : "100%",317                    zIndex : 1000,318                    elevation : 1000,319                    transform: [ { translateY : this.headerY }],320                    alignItems : "center",justifyContent : "center",321                    paddingTop : StatusBar.currentHeight,322                    flexDirection : "row"}}323                >324                  <Animated.View style={{position : "absolute",left : width*0.05 ,marginTop : -30}}>325                      <TouchableOpacity  onPress={() => this.props.navigation.goBack()  }>326                          <Ionicons name="md-arrow-round-back" size={30} color="white" />327                      </TouchableOpacity> 328                  </Animated.View>329                  <Animated.View style={{position : "absolute",left : width * 0.15 ,marginTop : -30}}>330                  <Avatar331                      size={50}332                      rounded333                      source={ this.state.foundUser.userProfile  ? { uri : this.state.foundUser.userProfile } : 334                      require("../../../assets/account.png") }335                  />336                  </Animated.View>337                  <Animated.View style={{position : "absolute",left : width * 0.30,marginTop : -30 }}>338                      <Text style={{color : "#fff",fontWeight : "bold",fontSize : 25, }}> {this.state.foundUser.userName} </Text>339                  </Animated.View>340              </Animated.View>341              <View style={{height : 80}} />342              <ScrollView 343                ref={ref => this.scrollView = ref}344                  style={[{minHeight : height-150 }]}345                  onContentSizeChange={(width, height)=>{        346                    this.scrollView.scrollToEnd({animated: true});347                  }}348                >349                  <List>350                    {this.state.messages.map( (item,index) => (351                      <View key={index} style={{width : "100%"}}>352                      { item._id == this.state.user.uid ?353                      <ListItem style={{flexDirection : "column"}}>354                        <Item style={{position : "absolute",left : 0,marginTop : 5}}>355                          <Text style={{color : "white",fontFamily : "Satisfy",}}> {this.state.user.name} </Text>356                        </Item>357                        <Item info style={[styles.messages,{backgroundColor : "#F5BCBA",marginTop : 20}]} >358                          <Text style={{color : "#000",fontFamily : "Caveat" ,fontSize : 20,}}> {item.text} 359                            {this.state.today != item.date.slice(0,11) ? 360                              <Text style={{fontSize : 14}}> ({item.date.slice(0,11)}) </Text> : <Text /> 361                            }362                            <Text style={{fontSize : 14}}> ({item.timestamp}) </Text> 363                          </Text>364                        </Item>365                      </ListItem>366                      : 367                      <ListItem style={{flexDirection : "column"}}>368                        <Item style={{position : "absolute",left : 0,marginTop : 15}}>369                            <Text style={{color : "white",fontFamily : "Satisfy",}}> {this.state.foundUser.name} </Text>370                        </Item>371                          <Item style={[styles.messages,{backgroundColor : "#FBD28B",marginTop : 30}]} >372                            <Text style={{color : "#000",fontFamily : "Caveat",fontSize : 17}}> {item.text}373                              {this.state.today != item.date.slice(0,11) ? 374                                <Text style={{fontSize : 14}}> ({item.date.slice(0,11)}) </Text> : <Text /> } 375                              <Text style={{fontSize : 10}}> ( {item.timestamp}) </Text> 376                            </Text>377                          </Item>378                      </ListItem> }379                    </View>380                    ) )}381                  </List>382                <Item style={{marginTop : 10,borderWidth : 3,borderColor : "red"}}>383                    <Input value={this.state.message} 384                      style={{flex : 12,color : "white",marginLeft : 10,fontFamily : "Caveat"}} 385                      onChangeText={ message => this.setState({ message }) } placeholder="Type message ...." 386                      placeholderTextColor="white"387                    />388                    {this.state.message == "" ? <View /> :  389                      <Button warning onPress={()=>{this.append(this.state.message)}} rounded style={{flex : 2}}>390                        <FontAwesome name="arrow-right" color="white" size={20} />391                      </Button> }392                  </Item> 393                <View style={{height : 15,zIndex : 0}} />394              </ScrollView>395            </GestureRecognizer>396        </KeyboardAvoidingView>397        );398    }399}400}401const styles = StyleSheet.create({402  container: {403    flex : 1404  },405  form : {406    position : "absolute",bottom : 0,width : "100%"407  },408  messages : {409    justifyContent : "space-between",alignItems : "center",width : "100%",minHeight : 50410  },...top-bottom-left-right-views-of-BT.js
Source:top-bottom-left-right-views-of-BT.js  
1/*2 * ****** All Views of a Binary Tree ****** *3*/4let topWidthBasedMap = [];5let bottomWidthBasedMap = [];6let leftHeightBasedMap = [];7let rightHeightBasedMap = [];8const formTopWidthBasedMap = (node, height, width) => {9    if (!node) {10        return;11    }12    let flag = false;13    let matchedIndex = -1;14    topWidthBasedMap.map((key, index) => {15        if (key.width === width) {16            flag = true;17            matchedIndex = index;18        }19    });20    if (flag) {21        if (topWidthBasedMap[matchedIndex].width === width && topWidthBasedMap[matchedIndex].height > height) {22            topWidthBasedMap[matchedIndex].height = height;23            topWidthBasedMap[matchedIndex].value = node.value;24        } else if (topWidthBasedMap[matchedIndex].width === width && topWidthBasedMap[matchedIndex].height === height) {25            topWidthBasedMap.push({ height, width, value: node.value });26        }27    } else {28        topWidthBasedMap.push({ height, width, value: node.value });29    }30    formTopWidthBasedMap(node.left, height + 1, width - 1);31    formTopWidthBasedMap(node.right, height + 1, width + 1);32};33const formBottomWidthBasedMap = (node, height, width) => {34    if (!node) {35        return;36    }37    let flag = false;38    let matchedIndex = -1;39    bottomWidthBasedMap.map((key, index) => {40        if (key.width === width) {41            flag = true;42            matchedIndex = index;43        }44    });45    if (flag) {46        if (bottomWidthBasedMap[matchedIndex].width === width && bottomWidthBasedMap[matchedIndex].height < height) {47            bottomWidthBasedMap[matchedIndex].height = height;48            bottomWidthBasedMap[matchedIndex].value = node.value;49        } else if (bottomWidthBasedMap[matchedIndex].width === width && bottomWidthBasedMap[matchedIndex].height === height) {50            bottomWidthBasedMap.push({ height, width, value: node.value });51        }52    } else {53        bottomWidthBasedMap.push({ height, width, value: node.value });54    }55    formBottomWidthBasedMap(node.left, height + 1, width - 1);56    formBottomWidthBasedMap(node.right, height + 1, width + 1);57};58const formLeftHeightBasedMap = (node, height, width) => {59    if (!node) {60        return;61    }62    let flag = false;63    let matchedIndex = -1;64    leftHeightBasedMap.map((key, index) => {65        if (key.height === height) {66            flag = true;67            matchedIndex = index;68        }69    });70    if (flag) {71        if (leftHeightBasedMap[matchedIndex].height === height && leftHeightBasedMap[matchedIndex].width > width) {72            leftHeightBasedMap[matchedIndex].width = width;73            leftHeightBasedMap[matchedIndex].value = node.value;74        }75    } else {76        leftHeightBasedMap.push({ height, width, value: node.value });77    }78    formLeftHeightBasedMap(node.left, height + 1, width - 1);79    formLeftHeightBasedMap(node.right, height + 1, width + 1);80};81const formRightHeightBasedMap = (node, height, width) => {82    if (!node) {83        return;84    }85    let flag = false;86    let matchedIndex = -1;87    rightHeightBasedMap.map((key, index) => {88        if (key.height === height) {89            flag = true;90            matchedIndex = index;91        }92    });93    if (flag) {94        if (rightHeightBasedMap[matchedIndex].height === height && rightHeightBasedMap[matchedIndex].width < width) {95            rightHeightBasedMap[matchedIndex].width = width;96            rightHeightBasedMap[matchedIndex].value = node.value;97        }98    } else {99        rightHeightBasedMap.push({ height, width, value: node.value });100    }101    formRightHeightBasedMap(node.left, height + 1, width - 1);102    formRightHeightBasedMap(node.right, height + 1, width + 1);103};104const printTopView = (node) => {105    formTopWidthBasedMap(node, 0, 0);106    topWidthBasedMap.sort((a, b) => (a.width - b.width));107    let printViewString = '';108    topWidthBasedMap.map((key, index) => {109        printViewString = printViewString + (key.value + ((index === topWidthBasedMap.length - 1) ? '' : ', '));110    });111    console.log(topWidthBasedMap);112    console.log('Top View of the given Binary Tree ->', printViewString);113};114const printBottomView = (node) => {115    formBottomWidthBasedMap(node, 0, 0);116    bottomWidthBasedMap.sort((a, b) => (a.width - b.width));117    let printViewString = '';118    bottomWidthBasedMap.map((key, index) => {119        printViewString = printViewString + (key.value + ((index === bottomWidthBasedMap.length - 1) ? '' : ', '));120    });121    console.log(bottomWidthBasedMap);122    console.log('Bottom View of the given Binary Tree ->', printViewString);123};124const printLeftView = (node) => {125    formLeftHeightBasedMap(node, 0, 0);126    leftHeightBasedMap.sort((a, b) => (a.height - b.height));127    let printViewString = '';128    leftHeightBasedMap.map((key, index) => {129        printViewString = printViewString + (key.value + ((index === leftHeightBasedMap.length - 1) ? '' : ', '));130    });131    console.log('Left View of the given Binary Tree ->', printViewString);132};133const printRightView = (node) => {134    formRightHeightBasedMap(node, 0, 0);135    rightHeightBasedMap.sort((a, b) => (a.height - b.height));136    let printViewString = '';137    rightHeightBasedMap.map((key, index) => {138        printViewString = printViewString + (key.value + ((index === rightHeightBasedMap.length - 1) ? '' : ', '));139    });140    console.log('Right View of the given Binary Tree ->', printViewString);141};142const mainFunctionForAllViews = () => {143    const node = {144        value: 1,145        left: {146            value: 2,147            left: { value: 4, left: { value: 8, left: null, right: null }, right: null },148            right: { value: 5, left: { value: 9, left: null, right: null }, right: null }149        },150        right: {151            value: 3,152            left: { value: 6, left: null, right: { value: 10, left: null, right: null } },153            right: { value: 7, left: null, right: { value: 11, left: null, right: null } }154        }155    };156    printTopView(node);157    // printBottomView(node);158    // printLeftView(node);159    // printRightView(node);160};...index.js
Source:index.js  
1const express = require("express");2const app = express();3const bodyParser = require("body-parser");4const port = 8080;5let studentArray = require("./InitialData");6let maxId = studentArray.length;7app.use(express.urlencoded());8// Parse JSON bodies (as sent by API clients)9app.use(express.json());10app.use(bodyParser.urlencoded({ extended: false }));11app.use(bodyParser.json());12// your code goes here13app.get("/api/student", (req, res) => {14  try {15    res.json(studentArray);16  } catch (error) {17    res.status(400).send({ message: error.message });18  }19});20app.get("/api/student/:id", (req, res) => {21  const student = studentArray.find((element) => {22    return element.id == req.params.id;23  });24  //   console.log(student);25  if (student) {26    res.json(student);27  } else {28    res.sendStatus(404);29  }30});31const isNullOrUndefined = (val) => val === null || val === undefined;32app.post("/api/student", (req, res) => {33  const { name, currentClass, division } = req.body;34  if (35    isNullOrUndefined(name) ||36    isNullOrUndefined(currentClass) ||37    isNullOrUndefined(division)38  ) {39    res.sendStatus(400);40  } else {41    let newId = maxId + 1;42    maxId = newId;43    const newStudent = {44      id: newId,45      name,46      currentClass: Number(currentClass),47      division,48    };49    studentArray.push(newStudent);50    console.log(studentArray);51    res.send({ id: newId });52  }53});54app.put("/api/student/:id", (req, res) => {55  const idToUpdate = req.params.id;56  const { name, currentClass, division } = req.body;57  const matchedIndex = studentArray.findIndex(58    (s) => s.id === Number(idToUpdate)59  );60  // console.log(matchedIndex);61  // console.log(studentArray[matchedIndex]);62  if (matchedIndex === -1) {63    res.sendStatus(400);64  } else {65    if (66      isNullOrUndefined(name) &&67      isNullOrUndefined(currentClass) &&68      isNullOrUndefined(division)69    ) {70      res.sendStatus(400);71    } else {72      if (!isNullOrUndefined(name)) {73        studentArray[matchedIndex].name = name;74        // res.sendStatus(200);75        // console.log(studentArray);76      }77      if (!isNullOrUndefined(currentClass)) {78        studentArray[matchedIndex].currentClass = Number(currentClass);79        // res.sendStatus(200);80      }81      if (!isNullOrUndefined(division)) {82        studentArray[matchedIndex].division = division;83        // res.sendStatus(200);84      }85      res.sendStatus(200);86    }87    // console.log(studentArray[matchedIndex]);88  }89});90app.delete("/api/student/:id", (req, res) => {91  const idToUpdate = req.params.id;92  const matchedIndex = studentArray.findIndex(93    (s) => s.id === Number(idToUpdate)94  );95  if (matchedIndex === -1) {96    res.sendStatus(404);97  } else {98    studentArray.splice(matchedIndex, 1);99    res.sendStatus(200);100  }101});102app.listen(port, () => console.log(`App listening on port ${port}!`));...Using AI Code Generation
1var mb = require('mountebank');2mb.create({3}, function (error) {4    if (error) {5        console.error(error);6    } else {7        console.log('running on port 2525');8    }9});10mb.post('/imposters', {11        {12                { is: { body: 'Hello world!' } },13                { is: { body: 'Goodbye world!' } }14        }15}, function (error, response) {16    var stubs = response.body.stubs;17});18mb.post('/imposters', {19        {20                { is: { body: 'Hello world!' } },21                { is: { body: 'Goodbye world!' } }22        }23}, function (error, response) {24    var stubs = response.body.stubs;25});26mb.post('/imposters', {27        {28                { is: { body: 'Hello world!' } },29                { is: { body: 'Goodbye world!' } }30        }31}, function (error, response) {32    var stubs = response.body.stubs;33});34mb.post('/imposters', {35        {36                { is: { body: 'Hello world!' }Using AI Code Generation
1var request = require('request');2var options = {3    json: {4            {5                    {6                        "is": {7                            "headers": {8                            },9                        }10                    }11            }12    }13};14request(options, function (error, response, body) {15    if (!error && response.statusCode == 201) {16        console.log(body)17    }18});19var request = require('request');20var options = {21    json: {22            {23                    {24                        "is": {25                            "headers": {26                            },27                        }28                    }29            }30    }31};32request(options, function (error, response, body) {33    if (!error && response.statusCode == 201) {34        console.log(body)35    }36});37var request = require('request');38var options = {39    json: {40            {41                    {42                        "is": {43                            "headers": {44                            },45                        }46                    }47            }48    }49};50request(options, function (error, response, body) {51    if (!error && response.statusCode == 201) {52        console.log(body)53    }54});55var request = require('requestUsing AI Code Generation
1var mb = require('mountebank');2var assert = require('assert');3mb.create({port:2525, pidfile: 'mb.pid', logfile: 'mb.log'}, function () {4    mb.post('/imposters', {protocol: 'http', port: 3000, stubs: [{responses: [{is: {body: 'Hello'}}]}]}, function () {5            assert.equal(response.body, 'Hello');6            console.log('Success!');7            process.exit(0);8        });9    });10});Using AI Code Generation
1var mb = require('mountebank');2var imposter = mb.create({3        {4                {5                    equals: {6                    }7                }8                {9                    is: {10                    }11                }12        }13});14imposter.then(function (imposter) {15    console.log('Imposter listening on port ' + imposter.port);16    console.log('Press CTRL-C to quit');17});18var mb = require('mountebank');19var imposter = mb.create({20        {21                {22                    equals: {23                    }24                }25                {26                    is: {27                    }28                }29        }30});31imposter.then(function (imposter) {32    console.log('Imposter listening on port ' + imposter.port);33    console.log('Press CTRL-C to quit');34});35var imposter = mb.create({36        {37                {38                    equals: {39                    }40                }41                {42                    is: {43                    }44                }45        }46});47imposter.then(function (imposter) {48    console.log('Imposter listening on port ' + imposter.port);49    console.log('Press CTRL-C to quit');50});Using AI Code Generation
1var mb = require('mountebank');2var assert = require('assert');3var Q = require('q');4var port = 2525;5var protocol = 'http';6var host = 'localhost';7var path = '/test';8var method = 'GET';9var imposterPort = 3000;10var imposterProtocol = 'http';11var imposterHost = 'localhost';12var imposterPath = '/test';13var imposterMethod = 'GET';14var imposterResponse = { 'hello': 'world' };15var imposterStatusCode = 200;16var imposterResponseHeaders = { 'Content-Type': 'application/json' };17var imposterPredicate = { 'equals': { 'path': '/test' } };18var imposterStub = { 'responses': [{ 'is': { 'statusCode': imposterStatusCode, 'headers': imposterResponseHeaders, 'body': imposterResponse } }] };19var imposterPredicateAndStub = { 'predicates': [imposterPredicate], 'stubs': [imposterStub] };20var imposterName = 'testImposter';21var imposter = { 'port': imposterPort, 'protocol': imposterProtocol, 'name': imposterName, 'stubs': [imposterStub] };22mb.create({ port: port, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto' })23    .then(function (api) {24        api.createImposter(imposter)25            .then(function (response) {26                assert.strictEqual(response.statusCode, 201, "Imposter creation failed");27                api.get('/imposters')28                    .then(function (response) {29                        assert.strictEqual(response.statusCode, 200, "Get imposters failed");30                        assert.strictEqual(response.body.imposters.length, 1, "Imposter not created");31                        api.get('/imposters/' + imposterPort)32                            .then(function (response) {33                                assert.strictEqual(response.statusCode, 200, "Get imposter failed");34                                assert.strictEqual(response.body.port, imposterPort, "Imposter port not correct");35                                assert.strictEqual(response.body.protocol, imposterProtocol, "Imposter protocol not correct");36                                assert.strictEqual(response.body.stubs.length, 1, "Imposter stubs not correct");37                                assert.strictEqual(response.body.stubs[0].responses.length, 1, "Imposter stubs not correct");38                                assert.strictEqual(responseUsing AI Code Generation
1var mb = require('mountebank');2var assert = require('assert');3var port = 2525;4mb.create({port: port, pidfile: "mb.pid", logfile: "mb.log"}, function (error) {5  if (error) {6    console.error("Failed to start mb: " + error.message);7  } else {8    console.log("mb started on port " + port);9    mb.post(server + "/imposters", {10        {11            {12              "is": {13              }14            }15        }16    }, function (error, response) {17      if (error) {18        console.error("Failed to create stub: " + error.message);19      } else {20        console.log("Stub created");21        mb.get(server + "/imposters/3000/matchedIndex", function (error, response) {22          if (error) {23            console.error("Failed to get matchedIndex: " + error.message);24          } else {25            console.log("matchedIndex: " + response.body);26            assert.strictEqual(response.body, "0");27            mb.get(server + "/imposters/3000/requests", function (error, response) {28              if (error) {29                console.error("Failed to get requests: " + error.message);30              } else {31                console.log("Requests: " + JSON.stringify(response.body));32                assert.strictEqual(response.body.length, 1);33                assert.strictEqual(response.body[0].request.method, "GET");34                assert.strictEqual(response.body[0].response.statusCode, 200);35                assert.strictEqual(response.body[0].response.body, "Hello, World!");36                mb.del(server + "/imposters/3000", function (error) {37                  if (error) {38                    console.error("Failed to delete stub: " + error.message);39                  } else {40                    console.log("Stub deleted");41                    mb.del(server + "/imposters", function (error) {42                      if (error) {43                        console.error("Failed to delete all stubs: " + error.message);44                      } else {Using AI Code Generation
1var imposter = require('mountebank').create();2var request = require('request');3imposter.post('/test', function (req, res) {4    res.send(200, req.body);5});6imposter.get('/test', function (req, res) {7    res.send(200, req.body);8});9imposter.start(2525, function () {10    request.post({11        json: { key: 'value' }12    }, function (error, response, body) {13    });14});15request.get({16        json: { key: 'value' }17    }, function (error, response, body) {18    });19var imposter = require('mountebank').create();20var request = require('request');21imposter.post('/test', function (req, res) {22    res.send(200, req.body);23});24imposter.start(2525, function () {25    request.post({26        json: { key: 'value' }27    }, function (error, response, body) {28    });29});30var imposter = require('mountebank').create();31var request = require('request');32imposter.post('/Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
