Mocking function inside object of another module (node + jest)

Viewed 369

I have two files inside my project:

controller.js

const controller = (request, response, route_name) => {
    parser[route_name](request.query, request.body, (err, data) => {
        ...
    }
};

export default controller;

parser.js

const parser = {
    foo: (query, body, callback) => {
        ...
        return callback(obj, null);
    }
};

export default parser;

Now, I am currently trying to test my controller. The first test is to send a bad formatted request and except the parser to call the callback with certain arguments. I have found no method or library to change how a function inside parser's object will behave. Can you guys help?

1 Answers

Assuming your are importing the parser module into controller.js like this

import parser from './parser`

you can easily mock the module like this in your test file:

jest.mock('./parser', () => ({ // note the path is relative to your test file
  foo: () => //your mock implementation here
}))

if you want test that parser.foo was called with the correct parameter you can make it a spy and import the parser into your test to check the correct call:

jest.mock('./parser', () => ({
  foo: jest.fn(() => //your mock implementation here)
}))
import parser from './parser'
import controller from './controller

controller(someRequestMock, someResponseMock, 'foo' )
expect(parser.foo).toHaveBeenCalledWith(...)
Related