Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

282
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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(...);
    });
  });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!