Search code examples
javascriptjestjswindowwidthscreen

How to test a function that uses the window.screen.width in jest


I'm trying to test this function in jest, But I cannot override, resize the screen or create a virtual dom.

I'm running this testing on node. ps: I tried to use jsdom but I failed.

functions.js

export const getScreenWidth = () => {
  const screenWidth = window.screen.width;
  if (screenWidth <= 425) return "mobile";
  if (screenWidth <= 768) return "tablet";
  if (screenWidth <= 1024) return "laptopSm";
  if (screenWidth <= 1440) return "laptopLg";
  if (screenWidth <= 2560) return "HD";
  return screenWidth;
};


Solution

  • I tried to make this mock and it worked but I don't really know if this is the right way to do so.

    const mockScreen = (size) => {
          global.window = {};
          global.window.screen = {};
          global.window.screen.width = size;
        };
    

    so the final test will be

    describe("getScreenWidth()", () => {
      it.only("returns a string representing the width of the screen", () => {
        const mockScreen = (size) => {
          global.window = {};
          global.window.screen = {};
          global.window.screen.width = size;
        };
        mockScreen(425);
        expect(jsf.getScreenWidth()).toBe("mobile");
        mockScreen(2560);
        expect(jsf.getScreenWidth()).toBe("HD");
      });
    });