使用反应测试库模拟 debounce util 函数或开玩笑不使用 lodash

Mock debounce util function using react testing library or jest not using lodash

我正在尝试模拟我的 debounce util 函数,但我的报道不足。一切都过去了,但我的 none 行有覆盖。我没有使用 _lodash。

Test.js

import { debounce } from '../../data/utils/utils';

afterEach(cleanup);

jest.useFakeTimers();

describe('debounce util', () => {
  const callback = jest.fn();

  beforeEach(() => {
    debounce(callback, 500);
  });

  it('should call debounce util', () => {
    for (let i = 0; i < 100; i++) {
      debounce(callback, 10);
    }
    jest.runAllTimers();
    expect(callback).toBeCalledTimes(0);
  });
});

Util.js

export const debounce = function debounce(fn, ms) {
  let timer;
  return () => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      timer = null;
      fn.apply(this, arguments);
    }, ms);
  };
};

在我看来,您没有正确测试去抖动功能。调用 debounce returns 一个新函数。您需要执行 return 函数。此外,您还应该测试在超时过去之前没有调用回调,并且在超时过去后恰好调用一次。

这是您测试的修改版本:

import { debounce } from '../../data/utils/utils';

afterEach(cleanup);

jest.useFakeTimers();

describe('debounce util', () => {
  const callback = jest.fn();

  beforeEach(() => {
    // Reset in case there are more test cases depending on the same mock
    callback.mockReset();
  });

  it('should call debounce util', () => {
    const debouncedCallback = debounce(callback, 10);
    for (let i = 0; i < 100; i++) {
      // Execute the debounced function
      debouncedCallback();
    }

    // Should not have been called yet since 10ms is not passed
    expect(callback).not.toHaveBeenCalled();

    // Fast forward time => 10ms will be passed
    jest.runAllTimers();

    // Now the callback should have been called exactly once
    expect(callback).toBeCalledTimes(1);
  });
});