개발/Today I Learned
Jest에서 window 객체 접근하기
devmomori
2022. 4. 26. 18:21
Notification, 또 브라우저의 URL에 관한 Unit Test를 작성하던 중 다음과 같은 에러를 마주했다.
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string. Consider using the "jsdom" test environment.
jest.config.js
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
transform: {
'\\.[jt]sx?$': 'babel-jest',
},
};
테스트환경은 node인데 window 객체를 가져오려면 jsdom 환경을 만들어주어야한다.
** 참고: node.js 환경에서의 테스트는 jsdom (브라우저) 환경에서의 테스트와 비교했을 때 훨씬 빠르다는 이점이 있다.
그러나, Notification, Window.location.href 와 같은 프로퍼티에 접근하지 못하기 때문에 jsdom을 사용 DOM 가상으로 접근하여 테스트를 진행해야 한다.
해결방법은 간단하다.
테스트를 진행하는 파일 맨 위에 해당 주석을 입력해주면 된다.
/**
* @jest-environment jsdom
*/
...test ongoing...
필요하다면 관련 패키지도 설치해준다.
yarn -D @jest-environment jsdom
clickNotification 함수는 window.location.href와 payloadURL을 비교 후 window.open을 실행한다.