似乎以下測驗應該具有相同的結果:
import {render, act} from '@testing-library/react';
test('async test', async () => {
let component;
await act(()=>{
component = render(<div/>);
});
console.log("logging");
expect(component).toBeTruthy();
});
test('without callback', () => {
let component;
act(()=>{
component = render(<div/>);
}).then(()=>{
console.log("logging");
expect(component).toBeTruthy();
});
});
具有以下內容package.json
:
{
"dependencies": {
"@testing-library/react": "^13.4.0",
"react-scripts": "5.0.1"
},
"scripts": {
"test": "react-scripts test --verbose",
"check": "jest --version"
}
}
第一個測驗按預期成功(我可以看到它的輸出),但第二個測驗輸出Cannot log after tests are done. Did you forget to wait for something async in your test?
.
為什么 jest 對在第二次測驗中的承諾延續中完成的日志記錄感到驚訝,而不是在第二次測驗中?
uj5u.com熱心網友回復:
第二個例子:沒有辦法知道它應該等待。
如果你不使用 async/await - 你必須在測驗函式中回傳一個 Promise 以便 jest 知道它是一個 Promise 并且它會等到 Promise 被解決/拒絕或超時過期。
所以代碼應該是這樣的:
test('without callback', () => {
let component;
return act(()=>{
component = render(<div/>);
}).then(()=>{
console.log("logging");
expect(component).toBeTruthy();
});
});
https://jestjs.io/docs/asynchronous#promises
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/506757.html
標籤:javascript 异步等待 承诺 开玩笑的 茉莉花