How to test for return result from callback in RTL?

Viewed 412

I expect callback to return either true or false. I know how to test for function being called, but how to test if that function returned specific value? How can I do that using react testing libraries?

My code:

it('sends back error callback', () => {
    const isError = (val) => val;
    render(<Component callback={isError}/>);
    const input = screen.getAllByRole('textbox')[0];
    fireEvent.change(input, {target: {value: '100.98'}});
    expect(isError).toHaveBeenCalledTimes(1);
  })
1 Answers

If you utilize a Mock (jest.fn()), you can simply use toHaveBeenCalledWith.

So in your case:

it("sends back error callback", () => {
  const isError = jest.fn();
  render(<Component callback={isError} />);
  const input = screen.getAllByRole("textbox")[0];
  fireEvent.change(input, { target: { value: "100.98" } });
  expect(isError).toHaveBeenCalledWith(false);
});

Or use this alternative, especially if you have issue with the asynchronous nature of the code:

it("sends back error callback", (done) => {
  const isError = (val) => {
    expect(val).toBe(false);
    done();
  };

  render(<Component callback={isError} />);
  const input = screen.getAllByRole("textbox")[0];
  fireEvent.change(input, { target: { value: "100.98" } });
});

Read more about async code: https://jestjs.io/docs/asynchronous.

If you have any questions to my answer/or the answer is not working, please get back to me in the comments .

Related