小编Tha*_*aen的帖子

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

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

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

        const { asFragment } = render(<MyComponent />);
        await waitFor(() => expect(asFragment()).toMatchSnapshot());
    })
})
Run Code Online (Sandbox Code Playgroud)

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

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

根据包的 eslint 规则,我必须像这样修改我的代码:

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

        const { asFragment } = render(<MyComponent />);
        expect(asFragment()).toMatchSnapshot();
    })
})
Run Code Online (Sandbox Code Playgroud)

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

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

reactjs jestjs react-testing-library snapshot-testing

2
推荐指数
1
解决办法
692
查看次数