
보통 next js 컴포넌트의 ui테스트를 할 때
it("render test", async () => {
render(<MyPage />);
expect(screen.getByText("complete")).toBeInTheDocument();
});
이런식으로 render 함수를 통해 렌더링 한 뒤 요소를 검사합니다.
그런데 react 18버전부터 도입된 서버컴포넌트 같은 경우 비동기 처리를 했을 경우 render함수에 argument로 컴포넌트를 JSX형식으로 넘겨줄 경우 아래와 같은 에러가 발생하게 됩니다.
> rsc-test@0.1.0 test
> jest
console.error
Error: Uncaught [Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.]
at reportException
...생략
11 |
12 | it("render test", async () => {
> 13 | render(<MyPage />);
| ^
14 | expect(screen.getByText("complete")).toBeInTheDocument();
15 | });
16 |
...생략
이는 아직까지 react-testing-library에서 서버 컴포넌트를 지원해주지 않아서 발생한 현상입니다.
현재까지는 임시 방편으로 아래와 같이 우회가 가능합니다.
it("test", async () => {
render(await MyPage());
expect(screen.getByText("complete")).toBeInTheDocument();
});
컴포넌트 역시 함수이기 때문에 JSX형식으로 아규먼트를 넘겨주는것이 아닌 await으로 비동기처리를 해준 뒤 함수를 호출하듯이 호출하면 정상적으로 테스트가 통과됩니다.
정상적으로 테스트가 통과 되기는 하지만 Next.js 공식 홈페이지에서는 아래와 같이 E2E테스트를 권장하고 있으니 고려해서 테스트 코드 작성이 필요할 것 같습니다.
Good to know: Since async Server Components are new to the React ecosystem, Jest currently does not support them. While you can still run unit tests for synchronous Server and Client Components, we recommend using an E2E tests for async components.
Next.js 공식 홈페이지
https://nextjs.org/docs/app/building-your-application/testing/jest
await을 통해 우회하는 방법
https://github.com/testing-library/react-testing-library/issues/1209