-2

I am trying to test the useState functionality which is also updates when useEffect is called.

The thing I am trying to test is at the initial stage the useState value is false then it changes on a click event.

Please see the code I tried below:

it("should have initial state false", async () => {
    const setStateMock = jest.fn();
    const useSateMock = (useState) => [useState, setStateMock];

    jest.spyOn(React, "useState").mockImplementation(useSateMock);

    render(<Dropdown placeholder="placeholder name" options={testOptions} />, { wrapper: BrowserRouter });
    const dropdwonBtn = screen.getByTestId("dropdownBtn");
    fireEvent.click(dropdwonBtn);
    expect(setStateMock).toBeFalsy();
});

The code of my dropdown component;

const [showDropdown, setShowDropdown] = useState(false);

useEffect(() => {
    const handler = () => setShowDropdown(false);

    window.addEventListener("click", handler);
    return () => {
        window.removeEventListener("click", handler);
    };
}, [""]);

const handleDropdownClick = (e) => {
    e.stopPropagation();
    setShowDropdown(!showDropdown);
};

the error I am getting

enter image description here Any help is appreciated thanks a million

Tapesh Patel
  • 131
  • 1
  • 17

1 Answers1

1

I am not sure you can mock the useState. But it is not something you should try.

Instead when your showDropdown value change from true to false. I guess your drop-down should become not visible. So make an assertion that it is visible before you click the button. Then use a userEvent to click the button and then check that the dropdown is not visible anymore.

Letincel
  • 197
  • 1
  • 8
  • Hi, @Letincel Thanks for the help and answer, one last thing? Should your test coverage report show 100% for all the components or functions? or is it that sometimes 92 is also good? my report says I have not covered two things one is the statement and the other is function. Please guide me on this. Thanks – Tapesh Patel Dec 14 '22 at 09:16