How to mock event object in React/Typescript with Jest?

Viewed 7949

I want to test that the console.log function is being called when the user presses the Enter key by an interactive HTMLElement. I've been trying to mock an event object of the function bellow in Jest with Typescript but it is not working. How to mock event object in React/Typescript with Jest?

Example:

import React from 'react';

function handleKey(event: React.KeyboardEvent) {
  if (event.key === 'Enter') {
    console.log('The enter key has been clicked');
  }
}
1 Answers

If the handler is a publicly consumable function, then call it with a plain object (you might have to do a type assertion)

console.log = jest.fn();
handleKey({ key: 'Enter' } as React.KeyboardEvent);
expect(console.log).toHaveBeenCalledWith('The enter key has been clicked');

If the handler you are testing is inside a component, you can call it indirectly by firing a keydown or keypress on the element that triggers the handler.

If you are using React Testing library, use fireEvent

const myInput = getByTestId(container, 'my-input')
fireEvent.keyPress(myInput, { key: 'Enter', keyCode: 13 })

If you are using Enzyme, use simulate

wrapper.find('input').simulate('keypress', {key: 'Enter'})

If RTL has issues with keypress, refer to https://github.com/testing-library/react-testing-library/issues/269

Related