【问题标题】:How can I test a debounce function with Jest/Enzyme?如何使用 Jest/Enzyme 测试去抖功能?
【发布时间】:2019-06-16 13:15:30
【问题描述】:

我有这个组件,测试覆盖率表明我需要测试第 24 行和第 25 行:

class TableToolbarComp extends Component {
  state = {
    shipmentId: '',
  };

  debouncedSetFilters = debounce(() => {
    const { applyFilters } = this.props; // LINE 24
    applyFilters(this.state);            // LINE 25
  }, 750);

  updateShipmentId = ev => {
    this.setState(
      {
        shipmentId: ev.target.value,
      },
      this.debouncedSetFilters,
    );
  };

  render() {...}
}

还有测试:

  beforeEach(() => {
    applyFilters: k => k,
  });

...

  it('should trigger button click', () => {
    const wrapper = shallow(<TableToolbarComp {...props} />);

    wrapper.instance().debouncedSetFilters(750);
    wrapper.instance().updateShipmentId({ target: { shipmentId: '124' } });
    wrapper.instance().props.applyFilters({ shipmentId: '124' });
  });

我没有收到任何错误,它只是说那 2 行需要覆盖。

我已经尝试在测试中调用 debouncedSetFiltersapplyFilters,但它仍然将这两行作为未覆盖返回。

我错过了什么?

【问题讨论】:

    标签: javascript reactjs ecmascript-6 jestjs enzyme


    【解决方案1】:

    没有间谍就无法有效地测试函数调用。应该是:

      beforeEach(() => {
        applyFilters = jest.fn();
      });
    

    为了测试异步时间敏感功能,应该应用计时器模拟:

    jest.useFakeTimers();
    
    const wrapper = shallow(<TableToolbarComp applyFilters={applyFilters} />);
    
    wrapper.instance().debouncedSetFilters();
    wrapper.instance().debouncedSetFilters();
    expect(applyFilters).not.toHaveBeenCalled();
    jest.advanceTimersByTime(750);
    expect(applyFilters).toHaveBeenCalledTimes(1);
    

    然后debouncedSetFilters 可以在updateShipmentId 测试中存根。

    【讨论】:

    • 为什么两次调用wrapper.instance().debouncedSetFilters(); 或者是拼写错误?
    • 这就是去抖动功能的测试方法。两次调用应导致一次 applyFilters 调用。
    猜你喜欢
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2018-11-09
    • 1970-01-01
    相关资源
    最近更新 更多