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