Categories
JavaScript Answers

How to mock a Node module with Jest?

Spread the love

Sometimes, we want to mock a Node module with Jest.

In this article, we’ll look at how to mock a Node module with Jest.

How to mock a Node module with Jest?

To mock a Node module with Jest, we can use the jest.createMockFromModule method.

For instance, we write

const utils = jest.createMockFromModule('../utils').default;
utils.isAuthorized = jest.fn(secret => secret === 'abc');

test('jest.createMockFromModule mocks utils module', () => {
  expect(utils.authorize.mock).toBeTruthy();
  expect(utils.isAuthorized('abc')).toEqual(true);
});

to call jest.createMockFromModule to mock the ./utils module.

Then we set utils.isAuthorized to a mocked function created by jest.fn with a callback to mock its implementation.

Next, we check if utils.authorize.mock is present with expect.

And we call utils.isAuthorized('abc') to see if it returns true as expected.

Conclusion

To mock a Node module with Jest, we can use the jest.createMockFromModule method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *