去抖动功能的Jest单元测试 [英] Jest unit test for a debounce function
问题描述
我正在尝试为去抖功能编写单元测试。我很难想到它。
I am trying to write a unit test for 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);
};
}
我该如何开始?
推荐答案
您可能需要检查去抖动函数中的逻辑:
You will probably want to check the logic in your debouncer function:
-
超时
将始终由最后一个设置if()
声明 -
此
将始终为undefined
,因为< a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this =noreferrer> arrow函数使用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屋!