I am currently experimenting with a function that adds logging and timing functionality to any function passed to it. However, I am facing a challenge when trying to test the timing aspect of it. Here are my functions:
//utils.js
export const util_sum = (x: number = 0, y: number = 0): number => x + y;
export const util_getTime = () => performance.now();
export const util_addTimeLogger = (fn: Function) => {
let t_start = util_getTime();
const beautify = JSON.stringify;
return (...args: any[]) => {
console.log(`entering ${fn.name}: ${beautify(args, null, 2)}`);
try {
const valueToReturn = fn(...args);
console.log(`normal exiting ${fn.name}: ${beautify(valueToReturn, null, 2)}`);
console.log(`--->total execution time:${util_getTime() - t_start}ms`);
return valueToReturn;
} catch (thrownError) {
console.log(`exception thrown ${fn.name}: threw ${thrownError}--->time:${util_getTime() - t_start}ms`);
throw thrownError;
}
}
};
Testing Section:
//util.test.js
describe("util_addTimeLogger", () => {
it("should add logging functionality with time to any functions", () => {
console.log = jest.fn();
const entering_msg = 'entering util_sum: [\n' +
' 1,\n' +
' 2\n' +
']';
const normal_msg = 'normal exiting util_sum: 3';
const total_time ='--->total execution time:0.47500000800937414ms';
const loggedSum = util_addTimeLogger(util_sum);
loggedSum(1,2);
expect(console.log).toHaveBeenCalledWith(entering_msg);
expect(console.log).toHaveBeenCalledWith(normal_msg);
expect(console.log).toHaveBeenNthCalledWith(total_time);
});
});
The issue lies in the third test, which is :
expect(console.log).toHaveBeenNthCalledWith(total_time.slice());
I have not been able to find a matcher like `toHaveBeencalledContainOf` or `subSetOf` as mentioned in the Jest document: https://jestjs.io/docs/en/expect.html
Is there a workaround for handling such situations?