Property ‘toBeInTheDocument’ does not exist on type ‘Matchers<any>’
Jest와 React Testing Library에서 toBeInTheDocument 타입 오류를 설정 파일로 해결하는 방법.
describe("UI 테스트", () => {
it("badge", () => {
const text = "이벤트";
render(<Badge>{text}</Badge>);
const badge = screen.getByText(text);
expect(badge).toBeInTheDocument();
});
});React + Typescript의 개발 환경에서 Jest + testing-library/react를 이용하여 테스트를 작성할 때, expect 단언에서 Matcher 메서드를 체이닝하면서 위와 같은 오류를 마주칠 수 있다.
Typescript의 타입 정의에 Jest 설정 파일이 제대로 연결되지 않아, Matcher와 같은 메서드 등을 인식하지 못하는 오류다. 그러나, 타입 인식의 문제이므로 Jest를 이용한 테스트 수행은 정상적으로 작동한다. 이 타입 인식 문제를 해결하려면, 타입 아래 공식 문서의 내용대로 정의한 Jest setup 파일을 tsconfig.json 내 “include” 배열에 넣어주면 된다.
// jest.setup.js
import "@testing-library/jest-dom";// tsconfig.json
{
"compilerOptions": {
/* ... */
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "./jest.setup.js"],
"exclude": ["node_modules"]
}@testing-library/jest-dom Custom jest matchers to test the state of the DOM. Latest version: 6.2.0, last published: 13 days ago. Start using…
www.npmjs.com
원문: Medium