Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Jest - Test preventDefault Action

I don't know how to test key down event & prevent default. Test reached code but preventDefault has never been called: Received number of calls: 0

React Component - App.js

  const onKeyDown = e => {
      console.log("==== TEST REACHED HERE ====")
      e.preventDefault(); // NEVER CALLED ???
  };
  useEffect(() => {
    document.addEventListener("keydown", onKeyDown, false);
    return () =>
      document.removeEventListener("keydown", onKeyDown, false);
  }, []);

Unit test

it("should prevent default action on key down", () => {
   const { getByRole } = render(<App {...props} />);
   const grid = getByRole("app");
   const mockEvent = { preventDefault: jest.fn() };
   fireEvent.keyDown(grid, mockEvent);
   expect(mockEvent.preventDefault).toHaveBeenCalledTimes(1);
});

enter image description here

like image 632
Klark Avatar asked Feb 28 '20 15:02

Klark


1 Answers

I found a more explicit way than accepted answer. You can use createEvent from 'react-testing-library' to manually create the event before firing it.

it("should prevent default action on key down", () => {
  const { getByRole } = render(<App {...props} />);
  const grid = getByRole("app");
  const keyDownEvent = createEvent.keyDown(grid);
   
  fireEvent(grid, keyDownEvent);
   
  expect(keyDownEvent.defaultPrevented).toBe(true);
});

I think this method can be reused to test other things than defaultPrevented !

like image 63
Pierre Ferry Avatar answered Sep 19 '22 09:09

Pierre Ferry