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

99
Views
How can I mock a function of other file that return a promise?

I have function below. I can't test this function using Jest framework.

The function:

exports.example = async function (data) {

let utility;
  if (data.flag) {
    utility = require('./utility');
  } else {
    utility = require(Runtime.giveFunctions()['utility'].path);
  }
  const valueFromUtility = await utility.getValue(data);
     .
     .
     .

From the test I pass the data object that contains several properties, including:

  • flag: if it is true I require the utility.js file and then I call the getValue (data) function, if it is false I get the path of the utility file that contains the getValue function and then I call the getValue (data) function.

If from the test pass data.flag === true the test is fine, otherwise (data.flag === false) the test fails telling me "utility.getValue is not a function".

In the utility.js file the getValue function returns a promise, as a parameter it has the data object which contains the mocked functions that will be called in getValue.

The test I wrote is the following:

test('Test with flag === false', async () => {

    jest.mock('../functions/utility', () => () => false);

    await example(data);

});

I also tried to mock the utility getValue function to return a resolved promise:

test('Test with flag === false', async () => {

    jest.mock('../functions/utility', () => jest.fn().mockReturnValue(Promise.resolve('Some values')));

    await example(data);

});

Finally, I mocked as follows:

const Runtime = {
    giveFunctions: jest.fn().mockReturnValue({
        utility: jest.fn().mockReturnValue({
            path: jest.fn()
        })
    })
};

window.Runtime = Runtime;

In the utility file I have only getValue function.

How can I solve this problem? Thanks everyone in advance

about 4 years ago · Juan Pablo Isaza
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!