6

I am writing an application in react which uses mousetrap. I want to know how the events of mousetrap can be tested in jest. I want to see whether a component function is being called when I click left arrow. I am not able to simulate this event in the test. It seems like events outside the synthetic events of react are not making any change to the component. I think Mousetrap attaches events to window. I need to know how to test this functionality.

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();

  });
prasadmsvs
  • 1,621
  • 4
  • 18
  • 31

1 Answers1

0

Try using document.documentElement instead of window and the following simulant fire syntax:

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();

  });
Adolfo
  • 798
  • 1
  • 7
  • 15