EN
JavaScript - express server Rest API mock with supertest and Jest
7
points
In this article, we would like to show how to testΒ Rest APIΒ using mocked modules with supertest
library andΒ Jest testing framework in JavaScript.
Quick solution:
const supertest = require('supertest')
it('GET /backend/path/to test', async () => {
jest.resetModules();
jest.doMock('../path/to/someServerModule', () => {
// ../path/to/someServerModule mock used by ./path/to/my/server
return {
// someServerModule logic here ...
};
});
// it is necessary to reload ./path/to/my/server module after mocks are defined
const app = require('./path/to/my/server');
const requester = supertest(app);
const response = await requester.get('/backend/path/to'); // by ./path/to/my/server
// response.body
});
Note: check GitHub repository.
Project details
Project structure:Β
.
βββ node_modules
βββ package.json
βββ package-lock.json
βββ src
βββ db.js
βββ index.js
βββ server.js
βββ test
βββ index.test.js
|
Running tests
Run the following command indicating test name:
node 'node_modules/.bin/jest' 'src/test/index.test.js' -t 'some feature'
Note: to install Jest, run in project directory:Β
npm install --save-dev jest
.
Example output:
PASS src/test/index.test.js
users api
β getting users (2546 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.374 s, estimated 30 s
Ran all test suites matching /\/home\/john\/Desktop\/jest-test\/src\/test\/index.test.js/i with tests matching "users api".
Waiting for the debugger to disconnect...
Running server
In this section, we would like to show when server is run in production mode.
Execute in the command line:
node src/index.js