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 handler(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 handler(data);
});
Finally, I mocked as follows:
const Runtime = {
giveFunctions: jest.fn().mockReturnValue({
utility: jest.fn().mockReturnValue({
path: jest.fn()
})
})
};
window.Runtime = Runtime;
How can I solve this problem? Thanks everyone in advance