Search code examples
reactjsnext.jsjestjsreact-testing-librarytesting-library

How to test screen orientation with jest and testing-library/react?


I wrote a test for a component in nextJs by testing-library/react and jestJs, and I checked "window.screen.orientation.type". I got an error that "TypeError: Cannot read properties of undefined (reading 'type')". How can I resolve this? How can I mock it to work?

I tried to use jest.spyOn :

jest.spyOn(window.screen, "orientation", "get").mockReturnValue();

but I don't know how to pass return value as ScreenOrientation and mock type field.

I also tried this:

jest.spyOn(window.screen.orientation, "type", "get") .mockReturnValue("portrait-primary");

and I got:

"Cannot spyOn on a primitive value; undefined given"


Solution

  • UPDATE:

    I found the solution for mocking orientation type and It's working now. I added this before render in test file:

    Object.defineProperty(window.screen, "orientation", {
        value: { type: "portrait-primary" },
      });