react testing fire event not triggering the window,onpopstate event

479 Views Asked by At

I have a code which will execute whenever we navigate thro bowser back/forward arrow click event. I need to test this event listener using the react testing library.

const useWindowPop = (switchOrg) => {
  useEffect(() => {
    window.onpopstate = (e) => {
      if (isLoggedIn) {
        const queryOrg = queryString.parse(window.location.search);
        if (queryOrg?.org) {
          switchOrg(queryOrg?.org);
        }
      }
    };
  }, []);
};

when I am trying to test this snippet using react-testing library, I am not able to get this event listener executed. I am trying test this like below:

it("fires history event on Window", () => {
  const switchOrg = jest.fn();
  renderHook(() => useWindowPop(switchOrg), {
    wrapper,
  });
  act(() => {
    fireEvent.popState(window);
  });
  fireEvent(
    window,
    new window.PopStateEvent("popstate", {
      location: "/track?org=123",
      state: { page: 1 },
    })
  );
  expect(switchOrg).toHaveBeenCalled();
});
1

There are 1 best solutions below

0
Lin Du On

It works fine for me. The popstate event is fired correctly.

E.g.

useWindowPop.ts:

import { useEffect } from "react";

export const useWindowPop = () => {
  useEffect(() => {
    window.onpopstate = (e) => {
      console.log(e.state);
    };
  }, []);
};

useWindowPop.test.ts:

import { fireEvent } from "@testing-library/react";
import { renderHook } from "@testing-library/react-hooks";
import { useWindowPop } from "./useWindowPop";

describe('75459671', () => {
  test('should pass', () => {
    renderHook(useWindowPop);

    fireEvent(
      window,
      new window.PopStateEvent("popstate", {
        state: { page: 1 },
      })
    );
  });
})

Test result:

 PASS  stackoverflow/75459671/useWindowPop.test.ts (7.007 s)
  75459671
    ✓ should pass (19 ms)

  console.log
    { page: 1 }

      at window.onpopstate (stackoverflow/75459671/useWindowPop.ts:6:15)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.279 s, estimated 8 s

package versions:

"@testing-library/react": "^11.2.7",
"@testing-library/react-hooks": "^8.0.1",
"jest": "^26.6.3",