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

Tha*_*aen 2 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());
    })
})
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)

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

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

Dou*_*oug 5

你走在正确的轨道上。剩下的唯一事情就是等待数据加载,然后再进行断言。

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

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

        expect(asFragment()).toMatchSnapshot();
    })
})
Run Code Online (Sandbox Code Playgroud)

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

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

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

        expect(asFragment()).toMatchSnapshot();
    })
})
Run Code Online (Sandbox Code Playgroud)

在注意到waitFor问题并修复它方面做得很好!