Languages
[Edit]
EN

JavaScript - create module mock in Jest

5 points
Created by:
Kadeem-Craig
516

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".
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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