testcode

ts환경의 jest에서 window.matchMedia is not a function 해결하기

냠냠맨 2023. 7. 26. 05:41

TypeError : window.matchMedia is not a function

정말 like dog같은 에러였습니다.

이게 저같은 경우에는 jest 파일 안에서 window.matchMedia를 사용하려는게 아니라

외부 컴포넌트에서 window.matchMedia를 사용하고있었기에

대부분의 솔루션들이 동작하지 않았습니다.

https://github.com/ant-design/ant-design/issues/21096

 

4.0.0-rc.1 TypeError: window.matchMedia is not a function in Jest · Issue #21096 · ant-design/ant-design

I have searched the issues of this repository and believe that this is not a duplicate. Reproduction link http://not/required/see/description Steps to reproduce Using react-testing-tools along with...

github.com

다행히 ant-design의 깃허브 이슈페이지에서 해결방법을 찾을 수 있었는데요

Thanaen씨.. 당신이 어느 나라 사람인지 몇살인지는 모르겠지만

복 많이 받으시길 발바니다.

 

Thanaen씨의 솔루션에 따르면 setupTest.js파일에 window.matchMedia 메서드를 mock하면 해결된다고합니다.

 

setupTest.ts 

import '@testing-library/jest-dom/extend-expect';
Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: jest.fn().mockImplementation((query) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: jest.fn(), // deprecated
    removeListener: jest.fn(), // deprecated
    addEventListener: jest.fn(),
    removeEventListener: jest.fn(),
    dispatchEvent: jest.fn(),
  })),
});

따라서 위와같이 코드를 작성해주었습니다.

에러가 해결되기 전에는 위와 같은 에러가 반환되었습니다.

 

이제 잘 동작합니다...

휴..

반응형