qq_花開花謝_0
2023-05-11 16:12:48
問題已確定。在實(shí)際的代碼庫中,斷言被傳遞給一個(gè)導(dǎo)入的回調(diào),一旦回調(diào)執(zhí)行失敗的測試,它就會(huì)引發(fā)承諾拒絕。所以,這接近于測試的實(shí)際編寫方式:describe( "file system", () => { it( "should check if the file exists", async () => { call( async () => { const received = await fileExists(); const expected = true; expect( received ).toBe( expected ); }); });});并且復(fù)雜的回調(diào)以更簡單的方式呈現(xiàn)以產(chǎn)生相同的問題:export function call( callback) { callback();}- 更新 -以下代碼有效。為了更好的可見性,我從大型代碼庫中選取了一小部分代碼。如果我只運(yùn)行以下代碼,它會(huì)按預(yù)期工作。我認(rèn)為實(shí)際代碼庫中存在問題。@Flask 關(guān)于集中處理未處理的承諾拒絕的建議為這個(gè)問題增加了很大的價(jià)值??紤]以下測試:import fileExists, { call } from "./exists";describe( "file system", () => { it( "should check if the file exists", async () => { const received = await fileExists(); const expected = true; expect( received ).toBe( expected ); });});對于以下來源:import fs, { constants } from "fs";import { promisify } from "util";export default async function fileExists() { const path = ".nonexistent"; const access = promisify( fs.access ); try { await access( path, constants.F_OK ); } catch { return false; } return true;}什么時(shí)候fileExists 拒絕退貨false,UnhandledPromiseRejectionWarning收到不出所料. 但這無助于追蹤失敗測試的根源。對于同步測試,Jest 會(huì)顯示測試路徑(即file system ? should check if the file exists),這有助于跟蹤失敗測試的來源。實(shí)現(xiàn)異步測試的最佳方法是什么?
1 回答

茅侃侃
TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超22個(gè)贊
UnhandledPromiseRejectionWarning預(yù)計(jì)不會(huì)在這里。它不等同于失敗的測試,因?yàn)槿绻麛嘌酝ㄟ^,它不會(huì)阻止測試通過。這意味著代碼以錯(cuò)誤的方式編寫并且包含不受限制的承諾。
await它只有在測試中被省略時(shí)才會(huì)發(fā)生:
fileExists(); // no await
或者fileExists函數(shù)包含松散的未處理的承諾:
fileExists() {
whatever() // no return
.then(() => {
whatever() // no return
}) // no catch to suppress errors
}
這是一個(gè)很好的做法setupFiles:
process.on('unhandledRejection', console.error);
它提供比UnhandledPromiseRejectionWarning錯(cuò)誤堆棧更有用的輸出并允許調(diào)試問題。
添加回答
舉報(bào)
0/150
提交
取消