Christopher
Christopher

Reputation: 620

How to correctly mock event handlers with React Testing Library

I have a React component that takes a string and renders an audio player. This audio player has a few handlers:

handlePlay, handleError, handleSeek, etc.

I would like to write a few unit tests around the handlers, but I don't know what to mock. A coverage test show lines around the handlers in red - so I assume these are to be tackled, since I can't access the state to check for new values.

I got this far:

<button data-testid onClick={handlePlay}>Button</button>
...
const { queryByTestId } = render(<Player id="abc" />);
const button = queryByTestId("button");
fireEvent.click(button); 

The button is being clicked, but I don't know how to test whether the handler has been called at all.

I tried to mock the handler:

const handlePlay = jest.fn();
handlePlay.mockImplementation(() => { console.log("works.."} );
expect(handlePlay).toBeCalled(); // or toHaveBeenCalled

I get:

Expected number of calls: >= 1
Received number of calls: 0

How should I correctly mock my components very basic handlers, so I can then write some basic assertions.

Bear in mind these handlers aren't being passed down to the component, the component only takes a string.

Upvotes: 1

Views: 2258

Answers (1)

olle
olle

Reputation: 579

Any eventhandlers you define within your Player component are going to be tough to mock like that. You can spy on their side effects (e.g. console.log, new Audio(), usage of imported modules), but the eventhandler itself is protected from the outside.

If your eventlisteners aren't too tightly coupled with your component state, consider moving the definition of them outside the component, making them reusable, open for individual unit tests, and reachable for mocking in integration tests.

Upvotes: 2

Related Questions