unit-testing - 使用反应测试库或玩笑不使用 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);
};
};
解决方案
在我看来,您没有正确测试去抖动功能。调用 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);
});
});
推荐阅读
- java - 返回视频信息 Video Intelligence API
- python - 生成没有刻度和白色边框的opencv-image
- qt - Qt QTreeView 检查选定文件夹是否展开并实现树视图导航
- javascript - Sequelize 中的 .sync() 究竟是为了什么?
- bootloader - 如何在源代码中锁定引导加载程序 - U-boot
- javascript - 如何使用 jQuery 将 if 条件添加到 append() 中
- c# - 从 Azure Functions 中的 Azure 服务总线接收 JSON(Cosmos DB 文档)作为输入
- node.js - 检索 JWT 身份验证的证书/密钥时出现问题。(节点/Express/C#/IdentityServer)
- r - ggplot histogram 在闪亮的应用程序中失败
- r - 使用 ggplot2 绘制地图