【发布时间】:2021-03-02 04:25:41
【问题描述】:
我正在测试 React 组件中的一些异步行为,包括加载和错误状态。我通过使用设置状态的不同 describe 块来接近不同的状态,如下所示:
jest.spyOn(global, 'fetch');
describe('The App', () => {
const promiseWithDelay = (json, delay=0) =>
new Promise(resolve =>
setTimeout(
() => resolve({
ok: true,
json: () => json
}), delay
)
);
describe('given data loading', () => {
beforeEach(async () => {
global.fetch.mockImplementationOnce(() =>
promiseWithDelay(someData, 50)
);
await waitFor(() => render(<App />));
});
// ... successful tests for a loading state here
});
describe('some other tests', () => {
// ... more setup and other tests here
});
});
我正在通过模拟 fetch 来创建加载状态
测试都通过了,但我得到了Warning: Can't perform a React state update on an unmounted component. 错误,我认为这是因为第一个描述块中的render 在第二个describe 块中的测试开始运行之前没有完全解决。
为了清除错误,我原本想在第一个 describe 块中包含一个 afterAll 函数,以等待创建加载状态的 Promise 解决,如下所示:
describe('The App', () => {
// ... etc
describe('given data loading', () => {
beforeEach(async () => {
// ... etc
});
// ... successful tests for a loading state here
afterAll(async () => {
await waitFor(() => {
expect(screen.queryByTestId('some-rendered-content')).toBeInTheDocument();
});
});
});
describe('some other tests', () => {
// ... more setup and other tests here
});
});
这并没有清除错误,但是将 afterAll 函数更改为 afterEach 函数就可以了。
完全困惑,我添加了一些控制台日志记录以查看发生了什么,然后发现了这一点:
// afterEach console logs
beforeEach: Starting loading test
test: Testing loading
afterEach: Cleaning up from loading test
afterEach: Waiting for content to render
afterEach: Waiting for content to render
afterEach: Cleaned up from loading test
some other test: Starting next test
// afterAll console logs
beforeEach: Starting loading test
test: Testing loading
afterAll: Cleaning up from loading test
afterAll: Waiting for content to render
(console.error): Warning: Can't perform a React state update on an unmounted component. (etc.)
afterAll: Waiting for content to render
afterAll: Waiting for content to render
... afterAll: Waiting for content to render logs many times here
some other test: Starting next test
谁能解释这里的操作顺序以及可能导致afterAll 而不是afterEach 警告的原因?
【问题讨论】:
标签: javascript reactjs unit-testing jestjs react-testing-library