Angela Inniss
Angela Inniss

Reputation: 359

How do I test an onKeyDown event on the whole document page for a pop up?

I have a pop up and I would like to test that when I press ESC on my keyboard that the pop up closes. The functionality works however I want to get my test to pass. I don't know how to simulate a keyDown press on the whole document and not just the Modal pop up component.

Here it my test right now:

  test("it should call the onKeyDown handler on key ESC press", () => {
    const onKeydownSpy = jest.fn();
    const component = mount(
      <div id="wrapper">
        <Modal
          isOpen={false}
          portalParent="#wrapper"
          onClose={() => {}}
          id="123"
        >
          <p>Modal</p>
        </Modal>
      </div>
    );

    component.simulate("keydown", { keyCode: 27 });
    expect(onKeydownSpy).toHaveBeenCalledTimes(1);
    expect(onKeydownSpy).toHaveBeenCalledWith(0);
  });

Here is my code:

  const handleKeyDownEvent = useCallback(event => {
    if (event.keyCode === 27) {
      onClose();
    }
  }, []);

  useEffect(() => {
    if (isOpen) {
      document.addEventListener("keydown", handleKeyDownEvent);
    } else {
      document.removeEventListener("keydown", handleKeyDownEvent);
    }
  }, [handleKeyDownEvent, isOpen]);

Thanks in advance, let me know if you need more information

Upvotes: 0

Views: 419

Answers (2)

Badrush
Badrush

Reputation: 1287

Does this solve your problem?

simulant.fire(document.body.querySelector('aside'), 'click')

 it('only triggers clickOutside handler when clicking outside component', t => {
    const onClickOutside = sinon.spy()
    enter code here
    ReactDOM.render(<Page onClickOutside={onClickOutside} />, document.body)
    simulant.fire(document.body.querySelector('aside'), 'click')
    t.equal(onClickOutside.callCount, 1, 'should fire when clicking menu sibling')
    document.body.innerHTML = ''
    t.end()
  })

Source: https://github.com/airbnb/enzyme/issues/426

Upvotes: 0

JP Silvashy
JP Silvashy

Reputation: 48525

I think the issue you're having is the document or one of the child elements needs to have the current "focus", if you check this before sending the esc key, what do you get:

document.hasFocus();

And generically you can:

document.focus();

before emitting your keys.

Upvotes: 1

Related Questions