【发布时间】:2020-05-11 09:49:17
【问题描述】:
我正在测试一个函数,它为传递给它的任何函数添加了日志记录和计时功能,所以我在测试计时部分时遇到了问题: 我的功能:
//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;
}
}
};
测试部分:
//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);
});
});
我的问题在第三个测试中,即:
期望(console.log).toHaveBeenNthCalledWith(total_time.slice());
我在文档中找不到像 tohaveBeencalledContainOf 或 subSetOf 这样的匹配器:https://jestjs.io/docs/en/expect.html
那么有什么办法可以处理这种情况吗?
【问题讨论】:
标签: javascript typescript unit-testing vue.js jestjs