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

132
Views
How can I test this function?

I have the following function which I can't test. I'm using Jest framework.

add.js

exports.sum = async function(flag, first, second) {
    let utility;
    if(flag) {
        utility = require('./newValue');
    } else {
        utility = require(Runtime.giveFunctions()['utility'].path);
    }

    const third = await utility.getThirdValue(first);

    //....
}

newValue.js

function getThirdValue(first) {
    return new Promise((resolve, reject) => {
        if(first % 2 === 0) {
            resolve(first);
        } else {
            console.log("Error");
            reject(null);
        }
    });
}
module.exports = {
    getThirdValue,
};

When I pass flag === true (in add.js) the test work correctly (because I require the original newValue.js file). When I try to pass flag === false the test fail and I receive the error 'utlity.getThirdValue is not a function'. This error appears when the function (add.js) call 'utility.getThirdValue(first)'. I think because there is no function when I mock Runtime.giveFunctions['utility'].path. In my test I write these rows:

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

window.Runtime = Runtime;

I can't use ES6, for this I'm searching a solution without 'import' statement. In my test I also tried to use jest.mock or jest.spyOn but the test still doesn't work. How can I solve? Thank's to all.

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!