reactjs - 如何对使用 react-testing-library 进行异步数据加载的组件进行快照测试?

标签 reactjs jestjs react-testing-library snapshot-testing

到目前为止,在我正在从事的项目中,我通常对我的组件进行快照测试,这些组件以这种方式加载异步数据:

describe('MyComponent component', () =>{
    test('Matches snapshot', async () => {
        fetch.mockResponse(JSON.stringify(catFacts));

        const { asFragment } = render(<MyComponent />);
        await waitFor(() => expect(asFragment()).toMatchSnapshot());
    })
})

我觉得它非常方便,因为它允许创建包含组件不同状态(加载、错误、加载数据)的快照。

问题是我刚刚发现这个方法是not recommended at all ,并且 @testing-library/react 包的最新更新不再允许我以这种方式测试我的组件。

根据包的eslint规则,我将不得不像这样修改我的代码:

describe('MyComponent component', () =>{
    test('Matches snapshot', () => {
        fetch.mockResponse(JSON.stringify(catFacts));

        const { asFragment } = render(<MyComponent />);
        expect(asFragment()).toMatchSnapshot();
    })
})

它可以工作,但生成的快照仅包含组件的初始状态(在本例中为“正在加载”)。

在这种情况下,您将如何有效地对异步加载数据的组件进行快照测试?

最佳答案

你在正确的轨道上。唯一剩下的就是等待数据加载完毕,然后再做出断言。

describe('MyComponent component', async () =>{
    test('Matches snapshot', () => {
        fetch.mockResponse(JSON.stringify(catFacts));
        
        const { asFragment } = render(<MyComponent />);

        await waitForElementToBeRemoved(screen.getByText('loading'));

        expect(asFragment()).toMatchSnapshot();
    })
})

我使用了 loading 文本,因为您在问题中提到了它。但您也可以等待您的数据出现在屏幕上:

await screen.findByText('something that comes from the mocked data');

注意到 waitFor 问题并修复它的工作做得很好!

关于reactjs - 如何对使用 react-testing-library 进行异步数据加载的组件进行快照测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64802563/

相关文章:

reactjs - 如何让 ant-design Drawer 组件宽度响应

reactjs - 如何等待子组件渲染

javascript - 关于 React js enzyme 中的状态

javascript - onChange 内的 React 测试函数

node.js - 为什么 Jest 没有在这个 Node 测试中完成异步操作?

reactjs - RTL 中的 waitForElementToBeRemoved 错误超时

react-testing-library - 如何在使用 react 测试库进行测试时渲染两个组件?

javascript - React spring过渡,实现每个元素的进入渐进式延迟

javascript - FileReader().readAsArrayBuffer(file) 结果在首次加载文件后卡住

javascript - 使用 JavaScript immutability-helper 或 {...data, } 更新数据集合中一条记录的一个字段