jeudi 7 février 2019

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)

Aucun commentaire:

Enregistrer un commentaire