【问题标题】:Test event listeners in enzyme/jest within useEffect在 useEffect 中的酶/玩笑中测试事件监听器
【发布时间】:2021-01-05 20:01:36
【问题描述】:

我的一个组件中有一段代码如下,如果用户使用 ESCAPE 键,模式将关闭:

    React.useEffect(() => {
    function keyListener(e) {
        if (e.key === 'Escape' || e.keyCode === escapeKey || e.which === escapeKey) {
            props.toggleShowModal();
        }
    }

    document.addEventListener('keydown', keyListener);

    return () => document.removeEventListener('keydown', keyListener);
});

我尝试了多种方式对此进行了测试,但没有任何效果,我尝试的最后一件事是:

    test('it calls the dismiss callback on ESC key', () => {
    global.document.addEventListener = jest.fn();

    const wrapper = mount(
        <Modal
            toggleShowModal={jest.fn()}
        />
    );
    expect(global.document.addEventListener).toHaveBeenCalled();

    const KEYBOARD_ESCAPE_CODE = 27;

    const spyOnToggleShowModal = jest.spyOn(wrapper.props(), 'toggleShowModal');
    var event = new KeyboardEvent('keydown', { key: 'Escape', keyCode: KEYBOARD_ESCAPE_CODE, which: KEYBOARD_ESCAPE_CODE });
    document.dispatchEvent(event);
    expect(spyOnToggleShowModal).toHaveBeenCalled();
});

【问题讨论】:

    标签: reactjs testing event-handling react-hooks enzyme


    【解决方案1】:

    我知道我迟到了,但这可能对某些人有帮助

    test("executes handler on escape keydown and unsubscribes after unmount", () => {
        const callback = jest.fn();
        const wrapper = mount(<Modal toggleShowModal={callback} />);
    
        document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
        expect(callback).toHaveBeenCalledTimes(1);
    
        wrapper.unmount();
    
        document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
        expect(callback).toHaveBeenCalledTimes(1);
      });
    

    注意document.dispatchEvent()。它可能需要在 window 或其他元素上调度,具体取决于添加 EventListener 的位置

    【讨论】:

      猜你喜欢
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 2023-03-27
      • 2019-09-13
      • 2019-11-10
      • 1970-01-01
      • 2021-01-26
      相关资源
      最近更新 更多