Mock function inside function with Jest

Viewed 1118

I would like to mock a function that is called inside another function and also control what it can return or possibly throw an error.

main.ts

import function from './function';

const main = async() => {
  ...
  try {
    value = await function(arguments);
  } catch(error) {
    ...
  }
}

For this dumb case for example if I wanted to test that "function" has been called with the right parameters, mocking its return value. I also want to be able to mock a thrown error from that function.

Basically I dont want my test to go inside this function, I just want to mock it and test the rest of the main function with the return value, and test the catch handler.

Here is the base of what I would want to do:

main.test.ts

import main from './main';
import function from './function';

describe('Test main', () => {
  it('should call function with the right arguments', async() => {
    function = jest.fn(() => value);
    await main();
    expect(function).toHaveBeenLastCalledWith(arguments);
    // expect not to have thrown error
  });
  it('should handle the error of function', async() => {
    function = jest.fn().mockRejectedValue(new Error('error'));
    await main();
    expect(function).toHaveBeenLastCalledWith(arguments);
    // expect to have thrown error
  });
});

Thank you for your help!

1 Answers

You need to mock the module.

Something like this:

import function from './function';

jest.mock("./function")

it("some", () => {
   function.mockRejectedValue(new Error('error'));
   //do stuff
   expect(function).toHaveBeenLastCalledWith(arguments);
});
Related