шутка: как проверить console.log haveBeenCalled с подмножеством ожидаемого значения? - PullRequest
0 голосов
/ 25 января 2020

Я тестирую функцию, которая добавляет функции ведения журнала и синхронизации к любой переданной ей функции, поэтому у меня возникла проблема с тестированием секции хронирования: мои функции:

//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

, так есть ли способ справиться с такими ситуациями?

1 Ответ

1 голос
/ 25 января 2020

Я нашел решение для этой ситуации, основываясь на шутке https://jestjs.io/docs/en/expect#expectstringcontainingstring:

Ожидаем. Строка (содержащая)

Ожидаем. stringContained (string) соответствует полученному значению, если это строка, которая содержит точную ожидаемую строку.

wait.stringMatching (string | regexp)

Ожидаем. 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));
    }
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...