【问题标题】:jest: how to test console.log haveBeenCalled with a subset of expected value?开玩笑:如何用期望值的子集测试 console.log haveBeenCalled?
【发布时间】: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


    【解决方案1】:

    我找到了解决这种情况的方法,基于 jest https://jestjs.io/docs/en/expect#expectstringcontainingstring:

    expect.stringContaining(字符串)

    expect.stringContaining(string) 匹配接收到的值,如果它是一个包含确切预期字符串的字符串。

    expect.stringMatching(string | regexp)

    expect.stringMatching(string | regexp) 如果接收到的值是匹配预期字符串或正则表达式的字符串。

    expect(console.log).toHaveBeenCalledWith(expect.stringMatching(/--->total execution time:0.*/));
    

    const total_time ='--->total execution time:0.';
    expect(console.log).toHaveBeenCalledWith(expect.stringContaining(total_time));
    

    更新: 为了完整起见,其他开发人员在测试错误部分可能会遇到类似问题。我们可以抛出错误,只是考虑你应该使用 try catch 将抛出的错误发送到正确的部分:

      it("should throw error with fn.name and it's calculated time", function () {
        const errorThrown = util_addTimeLogger(() => {
          throw new TypeError();
        });
        const error_msg = "exception thrown : threw TypeError--->time:";
        try {
          errorThrown();
        }
        catch (error) {
          expect(console.log).toHaveBeenCalledWith("entering : []");
          expect(console.log).toHaveBeenCalledWith(expect.stringContaining(error_msg));
        }
      });
    

    【讨论】:

      猜你喜欢
      • 2018-08-12
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      相关资源
      最近更新 更多