首页 > 解决方案 > 使用反应测试库或玩笑不使用 lodash 来模拟 debounce util 函数

问题描述

我试图模拟我的 debounce util 函数,但我的覆盖范围不足。一切都在过去,但我的台词都没有覆盖。我没有使用 _lodash。

测试.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);
  });
});

实用程序.js

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

标签: unit-testingjestjsreact-testing-librarydebounce

解决方案


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

这是您的测试的修改版本:

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);
  });
});

推荐阅读