fireEvent or data update only called once

Viewed 7

The function below is to test a custom multi-select component which returns a list of values to the onChange handler.

async function onChangeFunctionWorksMulti() {
  render(<BubbleSelect
    options={[{ value: 'Apple', testID: 'option1' }, { value: 'Cake', testID: 'option2' }]}
    onChange={(values:string | string[]) => console.log(values)}
    multi
  />);
  const consoleSpy = jest.spyOn(console, 'log');

  const appleOption = screen.getByTestId('option1');
  const cakeOption = screen.getByTestId('option2');
  expect(appleOption).toBeInTheDocument();
  expect(cakeOption).toBeInTheDocument();

  fireEvent.click(appleOption as HTMLButtonElement);
  expect(consoleSpy).toBeCalledWith(['Apple']);
  fireEvent.click(cakeOption as HTMLButtonElement);
  expect(consoleSpy).toBeCalledWith(['Apple', 'Cake']);
}

However, when running the test, only the first fireEvent function seems to be working because the first expect passes, but the second fails because it still holds the previous value.

Below is the error message:

 FAIL  src/tests/components/Utilities/BubbleSelect.test.tsx (40.348 s)
  ● onChange function is properly called (multi select)

    expect(jest.fn()).toBeCalledWith(...expected)

    - Expected
    + Received

      Array [
        "Apple",
    -   "Cake",
      ],

    Number of calls: 1

PS: I have tried it without using consoleSpy (with state and variable checking). Also, the implementation works properly. I have also tried it with waitFor

enter image description here

0 Answers
Related