Jest | Act Warning 해결법

쪼개발자·2023년 8월 29일

만약 데이터를 fetching 하는 react코드를 테스트 하는데 에러가 발생하는 경우,
이를 해결하는 방법을 정리해봅니다.

Act Warning 해결하는 방법

  • was not wrapped in act() 어쩌구 라는 경고가 떠도 굳이 act로 감쌀 필요가 없음.
    방법 1이 가장 좋은 방법, 4가 가장 나쁜 방법임.

1) 데이터 fetching 후 findBy, findAllBy를 사용할 것

useEffect(() => {
	icons.getClass(name)
    	.then((k) => setKlass(k))
        .catch(() => null);
}, [])

테스트 코드

test('', async () => {
	renderComponent();
	await screen.findByRole('img', { name: 'JavaScript'} );
 });

2) act 사용하여 해결

3) Jest.mock 사용
문제가 있는 부분이 FileIcon 렌더링 부분이라면, mock을 사용하여 문제가 되는 컴포넌트를 렌더링 하는걸 피할 것.

  • 실제로 fileIcon을 import하는게 아니라, 가짜로 렌더링된 것 처럼 하는 것
jest.mock('../tree/FileIcon', () => {
	return () => {
    	return 'File Icon Component'
    };
)}

4) act + pause 사용 - 비추!

아래는 자동으로 'act'를 호출함. act로 감쌀 필요가 사실 없음.
screen.findBy
screen.findAllby
waitFor
user.keyboard(async)
user.click(async)

import { act } from '@testing-library/react'

test('', async () => {
	renderComponent();
	await act(async () => {
    	await pause();
    });
 });
 
 const pause = () => new Promise(resolve => setTimeout(resolve, 100));

Data Fetching in Tests
1) 실제 네트워크로 요청하지 않음 - 느림
2) fake데이터로 테스트 할 것

  • 테스트 하는 법
    1) mock the file that contains the data fetching code.
    2) 'Mock' axios를 위한 Library 사용 (msw library)
rest.get('/api/repositories', (req, res, ctx) => {
  return res(
    ctx.json([
    ]),
 )
})

0개의 댓글