How to do the unit testing of history.push function?

Viewed 34

I want to unit test the following element, especially the onClick function, But have no idea how to do the unit testing

const baseURL = "/Security/Users/";


return (
    <div>
      <div className="flex-between">
        <button
          className="bt-save"
          onClick={() => history.push(baseURL + "Add")}
        >
          Add
        </button>
       </div>
    </div>
  );

this is related to react unit testing using jest. From this, I want to unit test the Add Button onClick function.

Here is my approach to unit test this function

it('Should run the callback function when clicked', async () => {
    const onClick = jest.fn(baseURL + "Add")

    render(<button push={onClick}> Add </button>)

    const addButton = screen.getByText('Add')
    await userEvent.click(addButton)
    expect(onClick).toHaveBeenCalled()
})

I'm getting the following error when I'm trying to do the testing.

I'm getting this result on the console

Can anyone help me understand this onClick function unit testing

1 Answers

You can accept an event callback as a prop of the component:


        <button
          className="bt-save"
          onClick={() => props.onAdd()}
        >

Then you can unit test using React Testin Library:


it("Should call onSave callback when clicking Add", async () => {
  const onAddMock = jest.fn();
  render(<MyComponent onAdd={onAddMock} />);

  await userEvent.click(screen.getByText("Add"));

  expect(onAddMock).toHaveBeenCalled();
}


Related