'How can I mock a function which is in other file and that return a promise?

I'm writing a Jest test. I need to test a function that calls a function in another .js file. This called function returns a promise that resolves to a string. When I start the test I get the error "file.function is not a function", where instead of "file" I have the name of the imported js file and instead of "function" I have the name of the function that return the promise.

Below my test:

test('test', () => {

     jest.mock('../file', () => {
         function: jest.fn().mockReturnValue('Returned String')
     });

     myFunction();
     expect().toBe();

});

Explanation: first of all I mocked the module which contains the function that return a promise. With second parameter (of jest.mock) I mocked the function contained in mocked module. Next I call the function that I want to test (this function will call mocked function). Finally, I test the expectations. Someone can help me, please. I don't know how I can resolve, thanks to all.



Solution 1:[1]

jest.mock should be at the same level as imports. If you need to test multiple cases just mock the returned/resolved value each time.

import { myFunction } from './fn';
import { function } from '../file';
jest.mock('../file', () => {
    function: jest.fn(),
});

describe('myFunction tests', () => {
  describe('With returned string', () => {
    beforeEach(() => {
      function.mockReturnValue('Returned String');
    });

    it('should do sth', () => {
      myFunction();
      // expect(...).toBe(...);
    });
  });

  describe('With returned number', () => {
    beforeEach(() => {
      function.mockReturnValue(7);
    });

    it('should do other thing', () => {
      myFunction();
      // expect(...).toBe(...);
    });
  });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Robin Michay