首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用react-testing-library和jest测试以useEffect格式获取数据并将其存储在状态中的组件?

如何使用react-testing-library和jest测试以useEffect格式获取数据并将其存储在状态中的组件?
EN

Stack Overflow用户
提问于 2021-11-23 18:13:43
回答 1查看 326关注 0票数 1

对于反应测试库和一般的测试,我还是个新手。我想测试一个从useEffect钩子中的API获取数据的组件。然后它将其存储在本地状态中。它使用array.map呈现这些数组数据,但我得到了Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'map')]错误。我可能在我的测试套件中做错了,我已经研究了很多,但无法修复它。

代码语言:javascript
运行
复制
    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.map代码的一部分:

代码语言:javascript
运行
复制
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>
EN

回答 1

Stack Overflow用户

发布于 2021-11-23 19:55:14

正如我预测的那样,问题出在异步数据获取上。目前setTimeOut对我来说已经足够了,但是如果将来有人看到这一点,你可以寻找waitFor的react-testing-library方法。下面是固定的部分:

代码语言:javascript
运行
复制
  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()
        })
    })
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70085859

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档