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

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

问题描述

我正在尝试为去抖功能编写单元测试。我很难想到它。

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 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天全站免登陆