EN
JavaScript - create module mock in Jest
5
points
In this article, we would like to show how to create a mock for a module using Jest testing framework in JavaScript.
Quick solution:
it('getting mocked module name', () => {
jest.resetModules();
jest.doMock('../module', () => {
// '../module' mock
return {
getName: () => 'mocked module.js'
};
});
// we need to reload the module
const {getName} = require('../module');
expect(getName()).toBe('mocked module.js');
});
Note: check GitHub repository.
Project details
Project structure:Β
.
βββ node_modules
βββ package.json
βββ package-lock.json
βββ src
βββ index.js
βββ module.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
some feature
β getting module name (18 ms)
β getting mocked module name (1 ms)
console.log
module.js
at Object.<anonymous> (src/module.js:1:1)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 0.92 s, estimated 15 s
Ran all test suites matching /\/home\/john\/Desktop\/jest-test\/src\/test\/index.test.js/i with tests matching "some feature".