有时候,在我更改API后,我的React应用程序在某些页面上崩溃了。现在,我想向应用程序中添加测试,以检查是否在进行API调用(所有调用都在componentDidMount()
函数内进行)后(重新)渲染组件而没有崩溃。
目前,我的测试非常简单,看起来像这样:
it(route.path + ' renders without crashing', async () => {
const div = document.createElement('div');
const Component = route.component;
ReactDOM.render(
<Provider store={store}>
<Component />
</Provider>
, div);
});
但是,这仅在API调用返回某些内容之前检查应用程序是否呈现。
如何添加类似await
的内容,以检查componentDidMount
中的数据是否已加载?
感谢您的帮助。
编辑
我签出了RTL,但仍然遇到问题。它总是说找不到元素。这是我的代码:
import { render, waitFor } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
test('examples of some things', async () => {
const { getByTestId, findByTestId } = render(
<Provider store={store}>
<Page />
</Provider>
);
await waitFor(() =>
expect(getByTestId("table")).toBeInTheDocument()
);
})
编辑2
<Page />
组件呈现一个<AnotherComponent />
,在此组件内部,进行了Ajax调用以加载一些数据,然后应将其呈现:
export default class Page {
render(
...
...
<AnotherComponent />
);
}
export default class AnotherComponent {
componentDidMount() {
someApiCall().then(set State...);
}
render(
....
...
{
this.state.someAPIdata &&
<div data-testid="table">
...
...
</div>
}
);
}
运行测试时,即使在API调用完成之前,测试已经返回了错误