GeraltDieSocke
GeraltDieSocke

Reputation: 1618

Why does the jest mock function not getting executed in my test with react testing library?

The Problem

I created a very basic code example for better clarification. Here is the code I want to test (containing simple react hook):

const TodoHeader = ({ handleSubmit }) => {
  const [value, setValue] = useState("");

  return (
    <form onSubmit={handleSubmit} data-testid="form">
      <input
        type="text"
        placeholder="Your Todo.."
        onChange={e => setValue(e.target.value)}
        value={value}
        data-testid="input"
      />
    </form>
  );
};

I want to test if the passed in handleSubmit prop will get executed. So I have set up this test:

it("should call the passed in onSubmit function", () => {
    const mockFn = jest.fn();

    const { getByTestId } = render(
      <TodoHeader handleSubmit={mockFn} />
    );
    const form = getByTestId("form");
    fireEvent.submit(form);
    // This will fail (did not get executed)
    expect(mockFn).toHaveBeenCalled();
  });

Has it something to do with react hooks? I also tried to rerender it but same result. I don't know why this won't pass. The error message is:

Expected mock function to have been called, but it was not called.

Here is a codesandbox if you want to play around with it:

https://codesandbox.io/s/ypok50n709 (TodoHeader.js and TodoHeader.test.js)

Upvotes: 2

Views: 1256

Answers (1)

Brian Adams
Brian Adams

Reputation: 45850

Looks like it's a simple problem, cleanup isn't actually getting called in afterEach. This means that there are two form elements rendered in document during the second test and getByTestId is returning the first one.

Change

afterEach(() => cleanup)

to either

afterEach(() => cleanup())

or just

afterEach(cleanup)

Upvotes: 3

Related Questions