munkee
munkee

Reputation: 769

Jest Mocking - Simple Mock

Jest mocking is really confusing me right now.

I have the following code in my notifications.js module:

// Dispatch notifications to MQTT end point
function dispatcher(shipment) {
  mqttclient.publish('notification', JSON.stringify(shipment));
  return console.info('Notification dispatched.');
}

I export this so it is available for my tests:

module.exports = { notificationProcessor, notificationDispatch, dispatcher };

I wish to change the implementation of this function during my tests so that the mqqtclient.publish event does not fire.

I have tried to mock the overall mqtt npm module which is also part of that file but it gets quite involved, so I split out the dispatcher function from my main code so I could focus purely on that.

dispatcher is called from notificationProcessor if a notification is identified. In my test file I am simply supplying the notificationProcessor with an email which is parsed and then issued out to the dispatcher.

How do I go about mocking the implementation of this simple function?

Upvotes: 0

Views: 2769

Answers (1)

Lewis Chung
Lewis Chung

Reputation: 2327

You can mock it without removing dispatcher out of the first module since dispatcher was an export.

in ./__mocks__/notifications.js

const notifications = require.requireActual('../notifications.js');

notifications.dispatcher = function(shipment) {
  // mock implementation
}

module.exports = notifications;

then in your test, you'd call jest.mock('path/to/notifications.js').

Quite simply, you are telling jest that anytime the notifications module is required, require the mock which actually loads the original module with a replaced dispatcher function and send that through.

Now there is a potential caveat ... in doing this, you're only changing the exports object, so it would only work if your notifications module calls dispatcher via module.exports.dispatcher.


if instead you don't want to call module.exports.dispatcher within your source file, yes you'll have pull dispatcher out into it's own module, but mocking it should look fairly similar.

in ./__mocks__/dispatcher.js

module.exports = function dispatcher(shipment) {
  // mock implementation
}

and call jest.mock('path/to/dispatcher.js') in your test.

Upvotes: 1

Related Questions