Cum de a testa o componenta care preia datele în useEffect și stochează în stat cu reacționa-testare-bibliotecă și o glumă, nu?

0

Problema

Sunt destul de nou pentru a reacționa-testare-bibliotecă și, în general, de testare. Vreau să testez o componenta care preia datele de la un API în useEffect cârlig. Apoi o stochează în stat locale. Acesta face aceste matrice de date cu matrice.harta, dar eu sunt obtinerea Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'map')] eroare. Probabil am greșit în suita de teste, am cercetat o mulțime, dar nu a putut repara.

    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()
        })
    })

Iar mai jos este părți de cod useEffect, și totalData.harta in componenta:

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

Cel mai bun răspuns

0

Așa cum am prezis, problema a fost asincron de date preluarea. În prezent setTimeOut este mai mult decât suficient pentru mine, dar daca cineva vede acest lucru în viitor, poti sa te uiti pentru waitFor metodă de a reacționa-testare-bibliotecă. Aici este partea fixă:

  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

În alte limbi

Această pagină este în alte limbi

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