2
votes

Jest has an option to mock node_module:

jest.mock('module_name')

Module I am trying to mock is cote module. Here is an index.js file from the module.

inside it has contructor for Requester exported

const Requester = require('./components/requester');

...

cote.Requester = Requester;

...

module.exports = cote();

I access this file in my code like this:

const cote = require('cote');
const requester = new cote.Requester({name: 'findOnePlayer requester'});

...

const player = await requester.send({type:'findOnePlayer',username:username, password: password})

How to set up with jest so that constructor of Requester from mocked cote module returns mocked object that resolves a promise when you call send?

EDIT: I need this case in many tests, and each send(... should return different promise per test scenario.

1

1 Answers

2
votes

A "manual mock" of the module that you first create in __mocks__, and then import into your tests using jest.mock('moduleName'), will allow you to mock the requester object in your code.

To generate different output each time requester.send() is called, one can make use of mock function implementations; i.e. jest.fn() and chained jest.mockImplementationOnce() invocations. For example:

const send = jest
  .fn(() => new Promise(resolve => resolve('foo')))
  .mockImplementationOnce(() => new Promise(resolve => resolve('bar')))
  .mockImplementationOnce(() => new Promise((resolve, reject) => reject()));

When you run successive tests where you execute this mocked send() function, the promises returned by send() will resolve with the values we specified above. For more details, check out the documentation here:

Manual mocks: https://jestjs.io/docs/en/manual-mocks

Mock Implementations: https://jestjs.io/docs/en/mock-functions#mock-implementations