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.