去抖动功能的 Jest 单元测试 [英] Jest unit test for a debounce function
问题描述
我正在尝试为 debounce 函数编写单元测试.我很难考虑.
I am trying to write a unit test for a debounce function. I'm having a hard time thinking about it.
这是代码:
function debouncer(func, wait, immediate) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
timeout = null;
if (!immediate)
func.apply(this, args);
}, wait);
if (immediate && !timeout)
func.apply(this, args);
};
}
我应该如何开始?
推荐答案
您可能需要检查 debouncer 函数中的逻辑:
You will probably want to check the logic in your debouncer function:
timeout
将始终由最后一个if()
语句设置this
将始终是undefined
,因为 箭头函数使用封闭词法上下文的this
值" 和debouncer()
旨在用作独立功能.
timeout
will always be set by that lastif()
statementthis
will always beundefined
since arrow functions use "thethis
value of the enclosing lexical context" anddebouncer()
is designed to be used as a stand-alone function.
话虽如此,听起来您真正的问题是关于测试去抖动函数.
Having said that, it sounds like your real question is about testing debounced functions.
您可以通过使用模拟来跟踪函数调用和使用假计时器来模拟时间的流逝来测试函数是否去抖动.
You can test that a function is debounced by using a mock to track function calls and fake timers to simulate the passage of time.
这是一个使用 Jest
模拟函数的简单示例 和 Sinon
假定时器函数使用 debounce()
来自 Lodash
:
Here is a simple example using a Jest
Mock Function and Sinon
fake timers of a function debounced using debounce()
from Lodash
:
const _ = require('lodash');
import * as sinon from 'sinon';
let clock;
beforeEach(() => {
clock = sinon.useFakeTimers();
});
afterEach(() => {
clock.restore();
});
test('debounce', () => {
const func = jest.fn();
const debouncedFunc = _.debounce(func, 1000);
// Call it immediately
debouncedFunc();
expect(func).toHaveBeenCalledTimes(0); // func not called
// Call it several times with 500ms between each call
for(let i = 0; i < 10; i++) {
clock.tick(500);
debouncedFunc();
}
expect(func).toHaveBeenCalledTimes(0); // func not called
// wait 1000ms
clock.tick(1000);
expect(func).toHaveBeenCalledTimes(1); // func called
});
这篇关于去抖动功能的 Jest 单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!