6

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

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

I would like to thank you for your answer. Unfortunately, in my case, I have to mock that event object. I know that it is a bad practice and I do not have to use it. Maybe that's the reason why there are no examples of such cases.
Indeed! I got you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.