728x90
반응형
경고 메세지
Warning: An update to Overlay inside a test was not wrapped in act(...).
act(...)로 코드를 감싸라는 권고사항으로서 테스트에는 성공하지만 현재 해당 프로젝트 코드에서는 act로 감싸면 안되는 경우에 있다.
해당 경고가 발생한다면 마운트 되지 않은 컴포넌트에서 React 상태 업데이트를 수행할 수 없다는 형제 경고를 동반한다.
When testing, code that causes React state updates should be wrapped into act(...):
이유
거의 대부분 해당 오류가 나는 이유는 테스트가 끝난 뒤 컴포넌트가 바뀌기 때문이다.
일부 비동기 상태 업데이트가 완료되기 전에 테스트 함수가 종료된다.
- 프로젝트 구성
OrderEntry(최상위) > Options(네트워크 호출하는 자식)
...
export default function OrderEntry() {
return (
<div>
<Options optionType="scoops" />
<Options optionType="toppings" />
</div>
);
}
...
export default function Options({ optionType }) {
const [items, setItems] = useState([]);
const [error, setError] = useState(false);
const { totals } = useOrderDetails();
useEffect(() => {
axios
.get(`http://localhost:3030/${optionType}`)
.then((response) => setItems(response.data))
.catch((error) => setError(true));
}, [optionType]);
...
- 현재 프로젝트 동작
OrederEntry Render > Options Component Render > Axios Call > Axios Response > Options Component Update
- 테스트 동작
OrderEntry Render > Options Component Render > Axios Call > Test Funtion Assertion Execute > Unmount Component > Test Success > Axios Response
이렇기 때문에 네트워크 호출이 반환되지 않은 상황에서 테스트가 종료되어 개발자가 고려하지 않은 무언가가 있다는 경고를 받은 것이다.
이는 네트워크 호출이 돌아오기 전에 컴포넌트가 언마운트되면 경합 조건으로 인해 오류가 트리거 되는 상황이다.
해결
이를 해결하기위해 우리는 네트워크 호출하는 과정은 그대로 두지만 컴포넌트 언마운트 시 클린업을 실행하고 명시적 언마운트를 진행할 것이다.
...
export default function Options({ optionType }) {
const [items, setItems] = useState([]);
const [error, setError] = useState(false);
const { totals } = useOrderDetails();
useEffect(() => {
// create an abortController to attach to the network request
const controller = new AbortController();
axios
// attach abortController to request
.get(`http://localhost:3030/${optionType}`, {
signal: controller.signal,
})
.then((response) => setItems(response.data))
.catch((error) => setError(true));
return () => {
// on unmount, abort any active requests
controller.abort();
};
}, [optionType]);
...
...test.jsx
test("grand total starts at $0.00", () => {
const { unmount } = render(<OrderEntry />);
const grandTotal = screen.getByText("Grand total: $", { exact: false });
expect(grandTotal).toHaveTextContent("0.00");
unmount();
});
...
728x90
반응형
'React > Jest' 카테고리의 다른 글
Jest Debugging Tips (0) | 2023.06.19 |
---|---|
JEST Custom Render (0) | 2023.06.16 |
Jest 원하는 테스트만 실행 (0) | 2023.06.15 |
JEST Mock Service Worker 테스트 내부 사용 (0) | 2023.06.15 |
JEST Mock Service Worker 설정 및 기본 사용 (0) | 2023.06.15 |