javascript - 对去抖函数进行单元测试以查看计时器是否在 500 毫秒后超时
问题描述
export const debounce = (func: (arg?: any) => void, timeOut: number = 500) => {
let timer: ReturnType<typeof setTimeout>;
return function(...args: any) {
if (timer) clearTimeout(timer);
timer = setTimeout(func, timeOut, ...args);
};
};
我正在尝试为此去抖动功能创建一个简单的测试。我该如何开始?
解决方案
我们可以模拟计时器jest.useFakeTimers();
我们可以确保我们的函数只有在超时后才被调用:
jest.useFakeTimers();
it('calls function after 500ms if timeout not been specified', () => {
const callback = jest.fn();
const debounced = debounce(callback);
debounced();
expect(callback).not.toHaveBeenCalled();
jest.advanceTimersByTime(499);
expect(callback).not.toHaveBeenCalled();
jest.advanceTimersByTime(2);
expect(callback).toHaveBeenCalled();
});
此外,您可能需要检查底层函数是否获得与您传递给去抖动版本相同的参数
it('passes same arguments down to callback', () => {
const callback = jest.fn();
const debounced = debounce(callback, 1);
debounced(1, 'a');
jest.advanceTimersByTime(2);
expect(callback).toHaveBeenCalledWith(1, 'a');
});
顺序调用会改变回调执行:
it('each call delay execution for specified timeout', () => {
const callback = jest.fn();
const debounced = debounce(callback, 50);
debounced();
jest.advanceTimersByTime(49);
debounced();
expect(callback).not.toHaveBeenCalled();
jest.advanceTimersByTime(49);
expect(callback).not.toHaveBeenCalled();
jest.advanceTimersByTime(2);
expect(callback).toHaveBeenCalled();
});
推荐阅读
- flutter - Fluro 不断在变量上返回空值(尝试从 url 获取参数)
- c# - 如何将数据从 WPF 应用程序发送到 UWP 应用程序?
- mongodb - MongoDB:从某个字段的最大值过滤的集合中获取所有文档
- c# - 如何获得 ContentPresenter 的父 ItemsControl?
- html - 如何使用 VBA 将我的 Excel 工作表中的信息输入到特定网站的搜索栏中?
- android - 我应该如何将 Android 中的原生构建应用升级到 Flutter 构建 Android?
- sap-cloud-platform - 使用 SAP Cloud SDK Pipeline 部署到 CF 时,Nodejs 应用程序间歇性地泄漏内存
- python-3.x - 在没有 POST 错误的情况下启动 flask-socketio
- python - 使用 Tensorflow 标记图像中的区域
- python - 使用资源策略对 API 网关的签名请求导致用户:匿名错误