DEV Community

Cover image for How to set up backend API mocks in JavaScript.
Gordon_Gao
Gordon_Gao

Posted on

How to set up backend API mocks in JavaScript.

Why mock an API?


There are many benefits of API Mocks:

  1. Developing frontend components that normally depend upon the services, when the services are not available;
  2. Testing frontend components (frontend unit tests generally use mocks for more reliability); and
  3. If backend and frontend development are happening in parallel, providing a contract/dummy response to work with whilst the backend is in development. ​ ## How to mock ​ In the following example, I will be using mountebank. There are other solutions out there, but we'll be using this one for the purposes of this article. ​
  4. Install mountebank globally: npm install -g mountebank
  5. Install the mountebank helper in your project: npm install mountebank-helper
  6. Create a file nameed mbSetting.js and write:

    const mbHelper = require("mountebank-helper");
    // create a imposter, and assign a port number to it
    const imposter = new mbHelper.Imposter({ imposterPort: 3430 });
    // define an object as HTTP response
    const mockResponse = {
      uri: "/structure",
      verb: "GET",
      res: {
        statusCode: 200,
        responseHeaders: { "Content-Type": "application/json" },
        responseBody: JSON.stringify({
          Contents: [{ Key: "content1" }, { Key: "content2" }]
        })
      }
    };
    // bind the response object to a route
    imposter.addRoute(mockResponse);
    // start mb server with routes set before
    mbHelper.startMbServer(2525).then(function() {
      imposter.postToMountebank().then(() => {
        console.log("Imposter Posted, domain is http://localhost:3430");
      });
    });
    

  1. Start the mountebank server: mb --nologfile
  2. Run the Node.js file you just created: node mbSetting.js
  3. Send an HTTP request to http://localhost:3430/structure, and the response from this endpoint should be:

     [{ Key: "content1" }, { Key: "content2" }]
    

Collapse

Top comments (1)

Collapse
 
jessekphillips profile image
Jesse Phillips

It looks like this requires setting up the mocking and running the server separately from the test. I prefer wiremock because of its rest api to define response within the test. But it is Java.