을 테스트하는 방법은 구성 요소를 가져오는 데이터에 useEffect 에 저장하는 상태로 반응하는 테스트-도서관 및 농담으?

0

질문

나는 상당히 새로운 반응하는 테스트-라이브러리와 일반적으로 테스트합니다. 고 싶 테스트 구성 요소를 가져오는 데이터에서는 API 를 useEffect 후크. 그 후에 저장하는 로컬 상태입니다. 렌더링 이러한 배열과 데이터 배열입니다.지도 있지만,나 Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'map')] 오류가 있습니다. 나는 가능하게 하는 잘못된 내에서 테스트,나는 연구를 많이하지만 해결할 수 없었습니다.

    import React from 'react';
    import { render, screen } from '@testing-library/react';
    import '@testing-library/jest-dom'
    import { rest } from 'msw';
    import { setupServer } from 'msw/node';

    import { OnePiece } from '.';

    const server = setupServer(rest.get('server http address', (req, res, ctx) => {
        const totalData = [
            { name: "doffy", price: 100, image: "image url" },
            { name: "lamingo", price: 500, image: "image url" }
        ];
        return res(
            ctx.status(200),
            ctx.json({
                data: { crew: totalData }
            })
        )
    }))
    beforeAll(() => server.listen());
    afterAll(() => server.close());
    beforeEach(() => server.restoreHandlers());

    //console.log("mocking axios", axios)
    describe('OnePiece', () => {
        
        test('fetches the data from the API and correctly renders it', async () => {
            //Here's probably where i fail. Please someone tell me the right way :) 
            await render(<OnePiece />)
            const items = await screen.findAllByAltText('product-image');
            expect(items).toHaveLength(2);
            //     screen.debug()
        })
    })

그리고 아래는 부분의 코드 useEffect 및 totalData.지도에서 구성 요소:

const [totalData, setTotalData] = useState([]);
const [crew, setCrew] = useState('straw-hat-pirates');

 useEffect(() => {
    let isApiSubscribed = true;
    const getOpData = async () => {
        const getCrews = await axios.get('http address');
        if (isApiSubscribed) {
            let data = getCrews.data;
            data = data[crew];
            // console.log("data", data);
            setTotalData(data);
        }
    }
    getOpData();
    return () => {
        isApiSubscribed=false;
    }
}, [crew])
.........

//in the return part
 <ProductsWrapper>
            {totalData.map((product, index) =>
                <ProductCard key={index} name={product.name} price={product.price} imageUrl={product.image} />
            )}
        </ProductsWrapper>
1

최고의 응답

0

로 예측되는 비동기 데이터를 가져오. 현재 setTimeOut 보다 더 나를 위해 충분히지만,누군가가 보면이 미래에 있을 수 있습니 waitFor 방법의 반응하는 테스트이 있는 점 양해 부탁드립니다. 여기에는 일부를 수정:

  describe('OnePiece', () => {
      test('fetches the data from the API and correctly renders it', async () => {
          render(<OnePiece />)
          setTimeout(async () => {
              const items = await screen.findAllByAltText('product-image');
              expect(items).toHaveLength(2);
            }, 4000)
            //screen.debug()
        })
    })
2021-11-23 19:55:14

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................