react dynamic import suspense unit test

김_리트리버·2022년 5월 16일
1

TDD

목록 보기
2/2

모듈을 dynamic import 로 불러오는 경우를 test 할 때는 일반적인 test 방법을 사용할 경우 test 가 통과하지 않는다.

이유는 suspense 에서 fallback 에 지정한 요소를 render 하고 , testingLibrary 에서는 해당 render 한 부분만을 확인하여 정상적으로 module 을 불러온 것에 대해서 test 가 되지 않았기 때문이다.

loading 요소가 사라진 후 test 하면 안되는 이유

describe('path 가/todos 이면', () => {
        it('todo 등록 form 출력', async () => {
            renderApp({ path: '/todos' })

            await waitForElementToBeRemoved(()=>screen.queryByTestId('Loading'))

            expect(screen.getByRole('heading')).toBeInTheDocument()
            expect(screen.getByTestId('TodoForm')).toBeInTheDocument()
        })
    })

    describe('path 가/todos/:id 이면', () => {
        beforeEach(() => {
            mockUseTodoState.mockImplementation(() => [{ ...todo, id: 3 }])
        })
        it('todo 등록 form 출력', async () => {
            renderApp({ path: '/todos/3' })

            await waitForElementToBeRemoved(()=>screen.queryByTestId('Loading'))

            expect(screen.getByRole('heading')).toBeInTheDocument()
            expect(screen.getByTestId('TodoForm')).toBeInTheDocument()
        })
    })

위의 예시 처럼 특정 test 가 먼저 module 을 불러올 경우 suspense 의 fallback 요소가 rendering 되지 않아 await waitForElementToBeRemoved() 에서 test 가 실패하기 때문에

describe('path 가/todos 이면', () => {
        it('todo 등록 form 출력', async () => {
            renderApp({ path: '/todos' })

            await screen.findByRole('heading')

            expect(screen.getByRole('heading')).toBeInTheDocument()
            expect(screen.getByTestId('TodoForm')).toBeInTheDocument()
        })
    })

    describe('path 가/todos/:id 이면', () => {
        beforeEach(() => {
            mockUseTodoState.mockImplementation(() => [{ ...todo, id: 3 }])
        })
        it('todo 등록 form 출력', async () => {
            renderApp({ path: '/todos/3' })

            await screen.findByRole('heading')

            expect(screen.getByRole('heading')).toBeInTheDocument()
            expect(screen.getByTestId('TodoForm')).toBeInTheDocument()
        })
    })

test 할요소를 찾을 때 까지 기다린 후 test expect 로 test 해야 정상적으로 test 를 진행할 수 있다.

실제 testingLibrary 제작자인 kentcdodds 도 위의 방법을 추천한다.

참고

https://testing-library.com/docs/guide-disappearance

https://github.com/kentcdodds/react-testing-library-examples/blob/main/src/tests/react-lazy-and-suspense.js

profile
web-developer

0개의 댓글