去抖动功能的 Jest 单元测试 [英] Jest unit test for a debounce function

查看:34
本文介绍了去抖动功能的 Jest 单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 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 will always be set by that last if() statement
  • this will always be undefined since arrow functions use "the this value of the enclosing lexical context" and debouncer() 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆