One place for hosting & domains

      How To Use Vue.js Environment Modes with a Node.js Mock Data Layer


      The author selected Open Sourcing Mental Illness to receive a donation as part of the Write for DOnations program.

      Introduction

      When it comes to software development, there are two ends of the stack. A stack is a collection of technologies used for your software to function. Vue.js, the progressive user interface framework, is part of the frontend, the part of the stack that a user directly interacts with. This frontend is also referred to as the client and encompasses everything that is rendered in the user’s browser. Technologies such as HTML, JavaScript, and CSS are all rendered in the client. In contrast, the backend commonly interacts with data or servers through technologies like Java, Kotlin, or .NET.

      The application is the data itself, and the interface (frontend) is a way to display data meaningfully to the user for them to interact with. In the begining phase of software development, you don’t need a backend to get started. In some cases, the backend hasn’t even been created yet. In a case such as this, you can create your own local data to build your interface. Using Node environments and variables, you can toggle different datasets per environment or toggle between local data and “live” data via a network call. Having a mock data layer is useful if you do not have data yet, because it provides data to test your frontend before the backend is ready.

      By the end of this tutorial, you will have created several Node environments and toggled these datasets with Node environment variables. To illustrate these concepts, you will create a number of Vue components to visualize this data across environments.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Creating Environments with Modes

      Modes are an important concept when it comes to Vue CLI projects. A mode is an environment type, or a set of variables that gets loaded during a build. These variables are stored in .env files in the root directory of your project. As part of the default vue-cli-service plugin, you immediately have access to three modes. These are:

      • development: used when vue-cli-service serve is executed.
      • test: used when vue-cli-service test:unit is executed.
      • production: used when vue-cli-service build and vue-cli-service test:e2e are executed.

      Perhaps the most used mode is development mode. This is the mode that Vue.js developers use when working on their application on their local machine. This mode starts a local Node server with hot-module reloading (instant browser refreshing) enabled. The test mode, on the other hand, is a mode to run your unit tests in. Unit tests are JavaScript functions that test application methods, events, and in some cases, user interaction. The last default mode is production. This compressess all of your code and optimizes it for performance so it can be hosted on a production server.

      The project that is generated for you from Vue CLI has these commands pre-mapped to npm run serve, npm run test:unit, and npm run build.

      Each environment is associated with its own .env file, where you can put custom Node environment key/value pairs that your application can reference. You will not have these files after generating a project from the CLI, but you can add these using one command in your terminal.

      You will now generate a development environment file, which you will use later in the tutorial. Open your terminal and enter the following in the root directory of your project:

      Open the newly created file in your text editor of choice. In this file, you’ll want to explicitly define the environment type. This is a key/value pair that could be anything you want. However, it’s considered best practice to define the environment type that corresponds with the name of the .env file.

      You will be using this NODE_ENV later in the tutorial by loading different data sets depending on the environment or mode selected on build. Add the following line:

      .env.development

      NODE_ENV="development"
      

      Save and exit the file.

      The key/value pairs in this file will only affect your program when the application is in development mode. It’s important to note that Git will automatically commit these files unless you add the file in your .gitignore file or append the .local extension to the file name: .env.development.local.

      You are not limited to the standard environments that Vue.js provides. You may have several other environments that are specific to your workflow. Next, you’ll create a custom environment for a staging server.

      Start by creating the .env file for the staging environment. Open your terminal of choice and in the root directory run the following:

      In this file, create a key/value pair that’ll define the NODE_ENV of this project. You may open this file in your text editor of choice, or you can modify it using the terminal. Nano is an editor that is used in the terminal window. You may have other editors such as Vim.

      You will be using this NODE_ENV later in the tutorial by loading different data sets depending on the environment or mode selected on build.

      Add the following to the file:

      .env.staging

      NODE_ENV="staging"
      

      Save and exit the file. In nano, you can save the file with CTRL+X then CTRL+Y.

      In order to use this environment, you can register a new script in your package.json file. Open this file now.

      In the "scripts" section, add the following highlighted line:

      package.json

      {
        ...
        "scripts": {
          ...
          "staging": "vue-cli-service serve --mode staging",
        },
        ...
      }
      

      Save this file, then exit the editor.

      You’ve just created a new script that can be executed with npm run staging. The flag --mode lets Vue CLI know to use the .env.staging (or .env.staging.local) file when starting the local server.

      In this step, you created custom NODE_ENV variables for two Vue.js modes: development and staging. These modes will come in handy in the following steps when you create custom datasets for each of these modes. By running the project in one mode or the other, you can load different data sets by reading these files.

      Step 2 — Creating a Mock Data Layer

      As stated in the Introduction, you can start developing your user interface without a backend by using a mock data layer. A mock data layer is static data that is stored locally for your application to reference. When working with Vue, these data files are JavaScript objects and arrays. Where these are stored is your personal preference. For the sake of this tutorial, mock data files will be stored in a directory named data.

      In this tutorial, you’re building a “main/detail” airport browser application. In the “main” view, the user will see a number of airport codes and locations.

      In your terminal, in the root project directory, create a new directory using the mkdir command:

      Now create a .js file named airports.staging.mock.js using the touch command. Naming these files is personal preference, but it’s generally a good idea to differentiate this mock data from essential files in your app. For the sake of this tutorial, mock files will follow this naming convention: name.environment.mock.js.

      Create the file with the following command:

      • touch data/airports.staging.mock.js

      In your editor of choice, open this newly created JavaScript file and add the following array of objects:

      data/airports.staging.mock.js

      const airports = [
          {
              name: 'Cincinnati/Northern Kentucky International Airport',
              abbreviation: 'CVG',
              city: 'Hebron',
              state: 'KY'
          },
          {
              name: 'Seattle-Tacoma International Airport',
              abbreviation: 'SEA',
              city: 'Seattle',
              state: 'WA'
          },
          {
              name: 'Minneapolis-Saint Paul International Airport',
              abbreviation: 'MSP',
              city: 'Bloomington',
              state: 'MN'
          }
      ]
      
      export default airports
      

      In this code block, you are creating objects that represent airports in the United States and providing their name, abbreviation, and the city and state in which they are located. You then export the array to make it available to other parts of your program. This will act as your “staging” data.

      Next, create a dataset for another environment like “development"—the default environment when running npm run serve. To follow the naming convention, create a new file in your terminal with the touch command and name it airports.development.mock.js:

      • touch data/airports.development.mock.js

      In your editor of choice, open this newly created JavaScript file and add the following array of objects:

      data/airports.development.mock.js

      const airports = [
          {
              name: 'Louis Armstrong New Orleans International Airport',
              abbreviation: 'MSY',
              city: 'New Orleans',
              state: 'LA'
          },
          {
              name: 'Denver International Airport',
              abbreviation: 'DEN',
              city: 'Denver',
              state: 'CO'
          },
          {
              name: 'Philadelphia International Airport',
              abbreviation: 'PHL',
              city: 'Philadelphia',
              state: 'PA'
          }
      ]
      
      export default airports
      

      This will act as your "development” data when you run npm run serve.

      Now that you’ve created the mock data for your environments, in the next step, you are going to iterate or loop through that data with the v-for directive and start building out the user interface. This will give you a visual representation of the change when using the different modes.

      Step 3 — Iterating Through Mock Data in App.vue

      Now that you have your mock data, you can test out how useful environments are by iterating through this data in the App.vue component in the src directory.

      First, open up App.vue in your editor of choice.

      Once it is open, delete all of the HTML inside the template tags and remove the import statement in the script section. Also, delete the HelloWorld component in the export object. Some general styles have also been provided to make the data easier to read.

      Add the following highlighted lines to your App.vue file:

      src/App.vue

      <template>
      
      </template>
      
      <script>
      export default {
        name: 'App',
      }
      </script>
      
      <style>
      #app {
        font-family: Avenir, Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        text-align: center;
        color: #2c3e50;
        margin-top: 60px;
      }
      
      .wrapper {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        grid-column-gap: 1rem;
        max-width: 960px;
        margin: 0 auto;
      }
      
      .airport {
        border: 3px solid;
        border-radius: .5rem;
        padding: 1rem;
      }
      
      .airport p:first-child {
        font-weight: bold;
        font-size: 2.5rem;
        margin: 1rem 0;
      <^>}
      
      .airport p:last-child {
        font-style: italic;
        font-size: .8rem;
      }
      </style>
      

      In this case, CSS Grid is being used to create these cards of airport codes into a grid of three. Notice how this grid is set up in the .wrapper class. The .airport is the card or section that contains each airport code, name, and location.

      Next, import the development mock data that was created earlier. Since this is vanilla JavaScript, you can import it via an import statement. You will also need to register this data with the data property so the Vue template has access to this data.

      Add the following highlighted lines:

      src/App.vue

      ...
      <script>
      import airports from '../data/airports.development.mock'
      
      export default {
        name: 'App',
        data() {
          return {
            airports
          }
        }
      }
      </script>
      ...
      

      Now that the mock data has been imported, you can start using it to build your interface. In the case of this application, iterate through this data with the v-for directive and display it in your template:

      src/App.vue

      <template>
        <div class="wrapper">
          <div v-for="airport in airports" :key="airport.abbreviation" class="airport">
            <p>{{ airport.abbreviation }}</p>
            <p>{{ airport.name }}</p>
            <p>{{ airport.city }}, {{ airport.state }}</p>
          </div>
        </div>
      </template>
      ...
      

      v-for in this case is used to render the list of airports.

      Save and close the file.

      In your terminal, start the development server by running the command:

      Vue CLI will provide you a local address, generally localhost:8080. Visit that addresss in your browser of choice. You will find the data from airports.development.mock.js rendered in your browser:

      Styled cards containing airport data from the development dataset.

      At this point, you created a static mock data layer and loaded it when you executed npm run serve. However, you will notice that if you stop the server (CTRL+C) and start the staging environment, you will have the same result in your browser. In this next step, you are going to tell your app to load a set of data for each environment. To achieve this, you can use a Vue computed property.

      Step 4 — Loading Environment-Specific Data with Computed Properties

      In Vue, computed properties are component functions that must return a value. These functions cannot accept arguments, and are cached by Vue. Computed properties are very useful when you need to perform logic and assign that return value to a property. In this respect, computed properties act similar to data properties as far as the template is concerned.

      In this step, you will use computed properties to use different datasets for the staging and the development environment.

      Start by opening src/App.vue and importing both sets of data:

      src/App.vue

      ...
      <script>
      import DevData from '../data/airports.development.mock'
      import StagingData from '../data/airports.staging.mock'
      
      export default {
        name: 'App',
        ...
      }
      </script>
      ...
      

      If you still have one of the environments running, your data will disappear. That is because you removed the data property that connected your JavaScript mock data to the template.

      Next, create a computed property named airports. The function name is important here because Vue is taking the return value of the function and assigning it to airports for the template to consume. In this computed property, you’ll need to write a bit of logic; an if/else statement that evaluates the Node environment name. To get the value of the Node environment in Vue, you can access it with process.env.NODE_ENV. When you created your Node environments, Vue automatically assigned NODE_ENV to development and staging respectively.

      src/App.vue

      ...
      <script>
      import DevData from '../data/airports.development.mock'
      import StagingData from '../data/airports.staging.mock'
      
      export default {
        name: 'App',
        computed: {
            airports() {
              if (process.env.NODE_ENV === 'development') return DevData
              else return StagingData
            }
        }
      }
      </script>
      ...
      

      Now you are loading each set of data per its respective environment.

      In your terminal, start the local development environment with npm run serve.

      The data will be identical to what it was before.

      Now, start the staging environment by first stopping the server and then executing npm run staging in your terminal window.

      When you visit localhost:8080 in your browser, you will find a different set of data.

      Styled cards containing airport data from the staging dataset.

      Conclusion

      In this tutorial, you worked with different Vue.js environment modes and added environment scripts to your package.json file. You also created mock data for a number of environments and iterated through the data using the v-for directive.

      By using this approach to make a temporary backend, you can focus on the development of your interface and the frontend of your application. You are also not limited to any number of environments or the default environments provided by Vue. It isn’t uncommon to have .env files for four or more environments: development, staging, user acceptance testing (UAT), and production.

      For more information on Vue.js and Vue CLI 3, it’s recommended to read through their documentation. For more tutorials on Vue, check out the Vue Topic Page.



      Source link

      How To Mock Services Using Mountebank and Node.js


      The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      In complex service-oriented architectures (SOA), programs often need to call multiple services to run through a given workflow. This is fine once everything is in place, but if the code you are working on requires a service that is still in development, you can be stuck waiting for other teams to finish their work before beginning yours. Additionally, for testing purposes you may need to interact with external vendor services, like a weather API or a record-keeping system. Vendors usually don’t give you as many environments as you need, and often don’t make it easy to control test data on their systems. In these situations, unfinished services and services outside of your control can make code testing frustrating.

      The solution to all of these problems is to create a service mock. A service mock is code that simulates the service that you would use in the final product, but is lighter weight, less complex, and easier to control than the actual service you would use in production. You can set a mock service to return a default response or specific test data, then run the software you’re interested in testing as if the dependent service were really there. Because of this, having a flexible way to mock services can make your workflow faster and more efficient.

      In an enterprise setting, making mock services is sometimes called service virtualization. Service virtualization is often associated with expensive enterprise tools, but you don’t need an expensive tool to mock a service. Mountebank is a free and open source service-mocking tool that you can use to mock HTTP services, including REST and SOAP services. You can also use it to mock SMTP or TCP requests.

      In this guide, you will build two flexible service-mocking applications using Node.js and Mountebank. Both of the mock services will listen to a specific port for REST requests in HTTP. In addition to this simple mocking behavior, the service will also retrieve mock data from a comma-separated values (CSV) file. After this tutorial, you’ll be able to mock all kinds of service behavior so you can more easily develop and test your applications.

      Prerequisites

      To follow this tutorial, you will need the following:

      Step 1 — Starting a Node.js Application

      In this step, you are going to create a basic Node.js application that will serve as the base of your Mountebank instance and the mock services you will create in later steps.

      Note: Mountebank can be used as a standalone application by installing it globally using the command npm install -g mountebank. You can then run it with the mb command and add mocks using REST requests.

      While this is the fastest way to get Mountebank up and running, building the Mountebank application yourself allows you to run a set of predefined mocks when the app starts up, which you can then store in source control and share with your team. This tutorial will build the Mountebank application manually to take advantage of this.

      First, create a new directory to put your application in. You can name it whatever you want, but in this tutorial we’ll name it app:

      Move into your newly created directory with the following command:

      To start a new Node.js application, run npm init and fill out the prompts:

      The data from these prompts will be used to fill out your package.json file, which describes what your application is, what packages it relies on, and what different scripts it uses. In Node.js applications, scripts define commands that build, run, and test your application. You can go with the defaults for the prompts or fill in your package name, version number, etc.

      After you finish this command, you'll have a basic Node.js application, including the package.json file.

      Now install the Mountebank npm package using the following:

      • npm install -save mountebank

      This command grabs the Mountebank package and installs it to your application. Make sure to use the -save flag in order to update your package.json file with Mountebank as a dependency.

      Next, add a start script to your package.json that runs the command node src/index.js. This script defines the entry point of your app as index.js, which you'll create in a later step.

      Open up package.json in a text editor. You can use whatever text editor you want, but this tutorial will use nano.

      Navigate to the "scripts" section and add the line "start": "node src/index.js". This will add a start command to run your application.

      Your package.json file should look similar to this, depending on how you filled in the initial prompts:

      app/package.json

      {
        "name": "diy-service-virtualization",
        "version": "1.0.0",
        "description": "An application to mock services.",
        "main": "index.js",
        "scripts": {
          "start": "node src/index.js"
        },
        "author": "Dustin Ewers",
        "license": "MIT",
        "dependencies": {
          "mountebank": "^2.0.0"
        }
      }
      

      You now have the base for your Mountebank application, which you built by creating your app, installing Mountebank, and adding a start script. Next, you'll add a settings file to store application-specific settings.

      Step 2 — Creating a Settings File

      In this step, you will create a settings file that determines which ports the Mountebank instance and the two mock services will listen to.

      Each time you run an instance of Mountebank or a mock service, you will need to specify what network port that service will run on (e.g., http://localhost:5000/). By putting these in a settings file, the other parts of your application will be able to import these settings whenever they need to know the port number for the services and the Mountebank instance. While you could directly code these into your application as constants, changing the settings later will be easier if you store them in a file. This way, you will only have to change the values in one place.

      Begin by making a directory called src from your app directory:

      Navigate to the folder you just created:

      Create a file called settings.js and open it in your text editor:

      Next, add settings for the ports for the main Mountebank instance and the two mock services you'll create later:

      app/src/settings.js

      module.exports = {
          port: 5000,
          hello_service_port: 5001,
          customer_service_port: 5002
      }
      

      This settings file has three entries: port: 5000 assigns port 5000 to the main Mountebank instance, hello_service_port: 5001 assigns port 5001 to the Hello World test service that you will create in a later step, and customer_service_port: 5002 assigns port 5002 to the mock service app that will respond with CSV data. If the ports here are occupied, feel free to change them to whatever you want. module.exports = makes it possible for your other files to import these settings.

      In this step, you used settings.js to define the ports that Mountebank and your mock services will listen to and made these settings available to other parts of your app. In the next step, you will build an initialization script with these settings to start Mountebank.

      Step 3 — Building the Initialization Script

      In this step, you're going to create a file that starts an instance of Mountebank. This file will be the entry point of the application, meaning that, when you run the app, this script will run first. You will add more lines to this file as you build new service mocks.

      From the src directory, create a file called index.js and open it in your text editor:

      To start an instance of Mountebank that will run on the port specified in the settings.js file you created in the last step, add the following code to the file:

      app/src/index.js

      const mb = require('mountebank');
      const settings = require('./settings');
      
      const mbServerInstance = mb.create({
              port: settings.port,
              pidfile: '../mb.pid',
              logfile: '../mb.log',
              protofile: '../protofile.json',
              ipWhitelist: ['*']
          });
      

      This code does three things. First, it imports the Mountebank npm package that you installed earlier (const mb = require('mountebank');). Then, it imports the settings module you created in the previous step (const settings = require('./settings');). Finally, it creates an instance of the Mountebank server with mb.create().

      The server will listen at the port specified in the settings file. The pidfile, logfile, and protofile parameters are for files that Mountebank uses internally to record its process ID, specify where it keeps its logs, and set a file to load custom protocol implementations. The ipWhitelist setting specifies what IP addresses are allowed to communicate with the Mountebank server. In this case, you're opening it up to any IP address.

      Save and exit from the file.

      After this file is in place, enter the following command to run your application:

      The command prompt will disappear, and you will see the following:

      • info: [mb:5000] mountebank v2.0.0 now taking orders - point your browser to http://localhost:5000/ for help

      This means your application is open and ready to take requests.

      Next, check your progress. Open up a new terminal window and use curl to send the following GET request to the Mountebank server:

      • curl http://localhost:5000/

      This will return the following JSON response:

      Output

      { "_links": { "imposters": { "href": "http://localhost:5000/imposters" }, "config": { "href": "http://localhost:5000/config" }, "logs": { "href": "http://localhost:5000/logs" } } }

      The JSON that Mountebank returns describes the three different endpoints you can use to add or remove objects in Mountebank. By using curl to send reqests to these endpoints, you can interact with your Mountebank instance.

      When you're done, switch back to your first terminal window and exit the application using CTRL + C. This exits your Node.js app so you can continue adding to it.

      Now you have an application that successfully runs an instance of Mountebank. In the next step, you will create a Mountebank client that uses REST requests to add mock services to your Mountebank application.

      Step 4 — Building a Mountebank Client

      Mountebank communicates using a REST API. You can manage the resources of your Mountebank instance by sending HTTP requests to the different endpoints mentioned in the last step. To add a mock service, you send a HTTP POST request to the imposters endpoint. An imposter is the name for a mock service in Mountebank. Imposters can be simple or complex, depending on the behaviors you want in your mock.

      In this step, you will build a Mountebank client to automatically send POST requests to the Mountebank service. You could send a POST request to the imposters endpoint using curl or Postman, but you'd have to send that same request every time you restart your test server. If you're running a sample API with several mocks, it will be more efficient to write a client script to do this for you.

      Begin by installing the node-fetch library:

      • npm install -save node-fetch

      The node-fetch library gives you an implementation of the JavaScript Fetch API, which you can use to write shorter HTTP requests. You could use the standard http library, but using node-fetch is a lighter weight solution.

      Now, create a client module to send requests to Mountebank. You only need to post imposters, so this module will have one method.

      Use nano to create a file called mountebank-helper.js:

      • nano mountebank-helper.js

      To set up the client, put the following code in the file:

      app/src/mountebank-helper.js

      const fetch = require('node-fetch');
      const settings = require('./settings');
      
      function postImposter(body) {
          const url = `http://127.0.0.1:${settings.port}/imposters`;
      
          return fetch(url, {
                          method:'POST',
                          headers: { 'Content-Type': 'application/json' },
                          body: JSON.stringify(body)
                      });
      }
      
      module.exports = { postImposter };
      

      This code starts off by pulling in the node-fetch library and your settings file. This module then exposes a function called postImposter that posts service mocks to Mountebank. Next, body: determines that the function takes JSON.stringify(body), a JavaScript object. This object is what you're going to POST to the Mountebank service. Since this method is running locally, you run your request against 127.0.0.1 (localhost). The fetch method takes the object sent in the parameters and sends the POST request to the url.

      In this step, you created a Mountebank client to post new mock services to the Mountebank server. In the next step, you'll use this client to create your first mock service.

      Step 5 — Creating Your First Mock Service

      In previous steps, you built an application that creates a Mountebank server and code to call that server. Now it's time to use that code to build an imposter, or a mock service.

      In Mountebank, each imposter contains stubs. Stubs are configuration sets that determine the response that an imposter will give. Stubs can be further divided into combinations of predicates and responses. A predicate is the rule that triggers the imposter's response. Predicates can use lots of different types of information, including URLs, request content (using XML or JSON), and HTTP methods.

      Looked at from the point of view of a Model-View-Controller (MVC) app, an imposter acts like a controller and the stubs like actions within that controller. Predicates are routing rules that point toward a specific controller action.

      To create your first mock service, create a file called hello-service.js. This file will contain the definition of your mock service.

      Open hello-service.js in your text editor:

      Then add the following code:

      app/src/hello-service.js

      const mbHelper = require('./mountebank-helper');
      const settings = require('./settings');
      
      function addService() {
          const response = { message: "hello world" }
      
          const stubs = [
              {
                  predicates: [ {
                      equals: {
                          method: "GET",
                          "path": "/"
                      }
                  }],
                  responses: [
                      {
                          is: {
                              statusCode: 200,
                              headers: {
                                  "Content-Type": "application/json"
                              },
                              body: JSON.stringify(response)
                          }
                      }
                  ]
              }
          ];
      
          const imposter = {
              port: settings.hello_service_port,
              protocol: 'http',
              stubs: stubs
          };
      
          return mbHelper.postImposter(imposter);
      }
      
      module.exports = { addService };
      
      

      This code defines an imposter with a single stub that contains a predicate and a response. Then it sends that object to the Mountebank server. This code will add a new mock service that listens for GET requests to the root url and returns { message: "hello world" } when it gets one.

      Let's take a look at the addService() function that the preceding code creates. First, it defines a response message hello world:

          const response = { message: "hello world" }
      ...
      

      Then, it defines a stub:

      ...
              const stubs = [
              {
                  predicates: [ {
                      equals: {
                          method: "GET",
                          "path": "/"
                      }
                  }],
                  responses: [
                      {
                          is: {
                              statusCode: 200,
                              headers: {
                                  "Content-Type": "application/json"
                              },
                              body: JSON.stringify(response)
                          }
                      }
                  ]
              }
          ];
      ...
      

      This stub has two parts. The predicate part is looking for a GET request to the root (/) URL. This means that stubs will return the response when someone sends a GET request to the root URL of the mock service. The second part of the stub is the responses array. In this case, there is one response, which returns a JSON result with an HTTP status code of 200.

      The final step defines an imposter that contains that stub:

      ...
          const imposter = {
              port: settings.hello_service_port,
              protocol: 'http',
              stubs: stubs
          };
      ...
      

      This is the object you're going to send to the /imposters endpoint to create an imposter that mocks a service with a single endpoint. The preceding code defines your imposter by setting the port to the port you determined in the settings file, setting the protocol to HTTP, and assigning stubs as the imposter's stubs.

      Now that you have a mock service, the code sends it to the Mountebank server:

      ...
          return mbHelper.postImposter(imposter);
      ...
      

      As mentioned before, Mountebank uses a REST API to manage its objects. The preceding code uses the postImposter() function that you defined earlier to send a POST request to the server to activate the service.

      Once you are finished with hello-service.js, save and exit from the file.

      Next, call the newly created addService() function in index.js. Open the file in your text editor:

      To make sure that the function is called when the Mountebank instance is created, add the following highlighted lines:

      app/src/index.js

      const mb = require('mountebank');
      const settings = require('./settings');
      const helloService = require('./hello-service');
      
      const mbServerInstance = mb.create({
              port: settings.port,
              pidfile: '../mb.pid',
              logfile: '../mb.log',
              protofile: '../protofile.json',
              ipWhitelist: ['*']
          });
      
      mbServerInstance.then(function() {
          helloService.addService();
      });
      

      When a Mountebank instance is created, it returns a promise. A promise is an object that does not determine its value until later. This can be used to simplify asynchronous function calls. In the preceding code, the .then(function(){...}) function executes when the Mountebank server is initialized, which happens when the promise resolves.

      Save and exit index.js.

      To test that the mock service is created when Mountebank initializes, start the application:

      The Node.js process will occupy the terminal, so open up a new terminal window and send a GET request to http://localhost:5001/:

      • curl http://localhost:5001

      You will receive the following response, signifying that the service is working:

      Output

      {"message": "hello world"}

      Now that you tested your application, switch back to the first terminal window and exit the Node.js application using CTRL + C.

      In this step, you created your first mock service. This is a test service mock that returns hello world in response to a GET request. This mock is meant for demonstration purposes; it doesn't really give you anything you couldn't get by building a small Express application. In the next step, you'll create a more complex mock that takes advantage of some of Mountebank's features.

      Step 6 — Building a Data-Backed Mock Service

      While the type of service you created in the previous step is fine for some scenarios, most tests require a more complex set of responses. In this step, you're going to create a service that takes a parameter from the URL and uses it to look up a record in a CSV file.

      First, move back to the main app directory:

      Create a folder called data:

      Open a file for your customer data called customers.csv:

      Add in the following test data so that your mock service has something to retrieve:

      app/data/customers.csv

      id,first_name,last_name,email,favorite_color 
      1,Erda,Birkin,ebirkinb@google.com.hk,Aquamarine
      2,Cherey,Endacott,cendacottc@freewebs.com,Fuscia
      3,Shalom,Westoff,swestoffd@about.me,Red
      4,Jo,Goulborne,jgoulbornee@example.com,Red
      

      This is fake customer data generated by the API mocking tool Mockaroo, similar to the fake data you'd load into a customers table in the service itself.

      Save and exit the file.

      Then, create a new module called customer-service.js in the src directory:

      • nano src/customer-service.js

      To create an imposter that listens for GET requests on the /customers/ endpoint, add the following code:

      app/src/customer-service.js

      const mbHelper = require('./mountebank-helper');
      const settings = require('./settings');
      
      function addService() {
          const stubs = [
              {
                  predicates: [{
                      and: [
                          { equals: { method: "GET" } },
                          { startsWith: { "path": "/customers/" } }
                      ]
                  }],
                  responses: [
                      {
                          is: {
                              statusCode: 200,
                              headers: {
                                  "Content-Type": "application/json"
                              },
                              body: '{ "firstName": "${row}[first_name]", "lastName": "${row}[last_name]", "favColor": "${row}[favorite_color]" }'
                          },
                          _behaviors: {
                              lookup: [
                                  {
                                      "key": {
                                        "from": "path",
                                        "using": { "method": "regex", "selector": "/customers/(.*)$" },
                                        "index": 1
                                      },
                                      "fromDataSource": {
                                        "csv": {
                                          "path": "data/customers.csv",
                                          "keyColumn": "id"
                                        }
                                      },
                                      "into": "${row}"
                                    }
                              ]
                          }
                      }
                  ]
              }
          ];
      
          const imposter = {
              port: settings.customer_service_port,
              protocol: 'http',
              stubs: stubs
          };
      
          return mbHelper.postImposter(imposter);
      }
      
      module.exports = { addService };
      
      

      This code defines a service mock that looks for GET requests with a URL format of customers/<id>. When a request is received, it will query the URL for the id of the customer and then return the corresponding record from the CSV file.

      This code uses a few more Mountebank features than the hello service you created in the last step. First, it uses a feature of Mountebank called behaviors. Behaviors are a way to add functionality to a stub. In this case, you're using the lookup behavior to look up a record in a CSV file:

      ...
        _behaviors: {
            lookup: [
                {
                    "key": {
                      "from": "path",
                      "using": { "method": "regex", "selector": "/customers/(.*)$" },
                      "index": 1
                    },
                    "fromDataSource": {
                      "csv": {
                        "path": "data/customers.csv",
                        "keyColumn": "id"
                      }
                    },
                    "into": "${row}"
                  }
            ]
        }
      ...
      

      The key property uses a regular expression to parse the incoming path. In this case, you're taking the id that comes after customers/ in the URL.

      The fromDataSource property points to the file you're using to store your test data.

      The into property injects the result into a variable ${row}. That variable is referenced in the following body section:

      ...
        is: {
            statusCode: 200,
            headers: {
                "Content-Type": "application/json"
            },
            body: '{ "firstName": "${row}[first_name]", "lastName": "${row}[last_name]", "favColor": "${row}[favorite_color]" }'
        },
      ...
      

      The row variable is used to populate the body of the response. In this case, it's a JSON string with the customer data.

      Save and exit the file.

      Next, open index.js to add the new service mock to your initialization function:

      Add the highlighted line:

      app/src/index.js

      const mb = require('mountebank');
      const settings = require('./settings');
      const helloService = require('./hello-service');
      const customerService = require('./customer-service');
      
      const mbServerInstance = mb.create({
              port: settings.port,
              pidfile: '../mb.pid',
              logfile: '../mb.log',
              protofile: '../protofile.json',
              ipWhitelist: ['*']
          });
      
      mbServerInstance.then(function() {
          helloService.addService();
          customerService.addService();
      });
      
      

      Save and exit the file.

      Now start Mountebank with npm start. This will hide the prompt, so open up another terminal window. Test your service by sending a GET request to localhost:5002/customers/3. This will look up the customer information under id 3.

      • curl localhost:5002/customers/3

      You will see the following response:

      Output

      { "firstName": "Shalom", "lastName": "Westoff", "favColor": "Red" }

      In this step, you created a mock service that read data from a CSV file and returned it as a JSON response. From here, you can continue to build more complex mocks that match the services you need to test.

      Conclusion

      In this article you created your own service-mocking application using Mountebank and Node.js. Now you can build mock services and share them with your team. Whether it's a complex scenario involving a vendor service you need to test around or a simple mock while you wait for another team to finish their work, you can keep your team moving by creating mock services.

      If you want to learn more about Mountebank, check out their documentation. If you'd like to containerize this application, check out Containerizing a Node.js Application for Development With Docker Compose. If you'd like to run this application in a production-like environment, check out How To Set Up a Node.js Application for Production on Ubuntu 18.04.



      Source link