DEV Community

Ronnie G. Chagas
Ronnie G. Chagas

Posted on

Mockando a propriedade window.screen com Jest

Para realizar um mock da propriedade window.screen e definir um valor padrão para realizar algum teste, basta usar utilizar a função jest.spyOn, disponibilizada pela lib de testes jest.

Por exemplo:

jest.spyOn(window.screen, "width", "get").mockReturnValue(1000);
console.log(window.screen.width);
Enter fullscreen mode Exit fullscreen mode

O resultado para o console.log acima irá retornar 1000.

O mesmo pode ser feito para a propriedade height.

Vamos ao exemplo:

jest.spyOn(window.screen, "height", "get").mockReturnValue(500);
console.log(window.screen.height);
Enter fullscreen mode Exit fullscreen mode

O resultado para o console.log acima irá retornar 500.

A seguir deixo um exemplo completo em React de uma implementação mockando a instância width da propriedade Screen.

React:

export const Menu = () => {
  const showMenuDesktop = window.screen.width > 400;

  return (
    <>
      {showMenuDesktop && (
        <MenuDesktop getByTestId="component-MenuDesktop" />
      )}
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

Teste unitário:

describe("Component MenuDesktop", () => {
  it("NÃO deve renderizar MenuDesktop em tela pequena", () => {
    jest.spyOn(window.screen, "width", "get").mockReturnValue(300);
    const { getByTestId } = render(<Menu/>);
    expect(getByTestId("component-MenuDesktop")).toBeFalsy();
  });

  it("Deve renderizar MenuDesktop em tela grande", () => {
    jest.spyOn(window.screen, "width", "get").mockReturnValue(1024);
    const { getByTestId } = render(<Menu/>);
    expect(getByTestId("component-MenuDesktop")).toBeTruthy();
  });
});
Enter fullscreen mode Exit fullscreen mode

💬 Dúvidas, sugestões ou críticas, utilize os comentários abaixo! 😉

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay