Languages
[Edit]
EN

JavaScript - create module mock in Jest

5 points
Created by:
JustMike
27910

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

src/test/index.test.js file:

describe('some feature', () => {
    // always we want to use default defined modules as initial state
    beforeEach(() => jest.resetModules());

    it('getting module name', () => {
        // we need to reload module
        const {getName} = require('../module');
        expect(getName()).toBe('module.js');
    });

    it('getting mocked module name', () => {
        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');
    });
})

src/index.js file:

const {getName} = require('./module');

console.log('index.js');
console.log(`Module name: ${getName()}`);

src/module.js file: <--- this module was reloaded in the test with mock

console.log('module.js');

exports.getName = () => 'module.js';

package.json file:

{
  "name": "jest-test",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {},
  "devDependencies": {
    "jest": "^26.6.3"
  }
}

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".
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join