Why mock an API?
There are many benefits of API Mocks:
- Developing frontend components that normally depend upon the services, when the services are not available;
- Testing frontend components (frontend unit tests generally use mocks for more reliability); and
- 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.
- Install mountebank globally:
npm install -g mountebank
- Install the mountebank helper in your project:
npm install mountebank-helper
-
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"); }); });
- Start the mountebank server:
mb --nologfile
- Run the Node.js file you just created:
node mbSetting.js
-
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)
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.
Wiremock as a Web Server for Testing
Jesse Phillips ・ Dec 1 ・ 1 min read