如何测试使用捕鼠器创建的事件以使用玩笑进行反应

pra*_*svs 6 mousetrap reactjs jestjs

我正在编写一个使用捕鼠器的反应应用程序。我想知道如何在玩笑中测试捕鼠器的事件。我想查看单击左箭头时是否正在调用组件函数。我无法在测试中模拟此事件。似乎反应的合成事件之外的事件没有对组件进行任何更改。我认为捕鼠器将事件附加到窗口。我需要知道如何测试这个功能。

it("checks on leftclick", () => {

    var spy = jest.spyOn(MyComponent.prototype, "onLeftClick");
    var wrapper = mount(<MyComponent />);
    var event = simulant( 'keyDown', { key: 37, which: 37 });
    simulant.fire(window, event); // It did not work
    ReactTestUtils.simulate.keyDown(window, { key: "ArrowLeft", keyCode: 37, which: 37 }) //Did not work either
    expect(spy).toHaveBeenCalled();
    spy.mockReset();
    spy.mockRestore();

  });
Run Code Online (Sandbox Code Playgroud)

Ado*_*lfo 0

尝试使用以下模拟火灾语法document.documentElement代替:window

it("checks on leftclick", () => {

    var spy = jest.spyOn(MyComponent.prototype, "onLeftClick");
    var wrapper = mount(<MyComponent />);
    simulant.fire(document.documentElement, "keydown", { keyCode: 37 });
    expect(spy).toHaveBeenCalled();
    spy.mockReset();
    spy.mockRestore();

  });
Run Code Online (Sandbox Code Playgroud)