- 更新 -
问题已经确定。
在实际的代码库中,断言被传递给导入的回调,一旦回调执行失败的测试,它就会引发承诺拒绝。
因此,这与测试的实际编写方式很接近:
describe( "file system", () => {
it( "should check if the file exists", async () => {
call( async () => {
const received = await fileExists();
const expected = true;
expect( received ).toBe( expected );
});
});
});
并且复杂的回调以更简单的方式呈现,以产生相同的问题:
export function call( callback) {
callback();
}
- 更新 -
以下代码有效。
我从大型代码库中选取了一小部分代码,以获得更好的可见性。如果我只运行下面的代码,它就会按预期工作。我认为实际的代码库存在问题。
@Flask 关于处理未处理的承诺拒绝的建议集中为这个问题增加了很大的价值。
考虑以下测试:
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;
}
When fileExists
rejects returns false
, an UnhandledPromiseRejectionWarning
is received as expected. But this does not help trace the source of the failed test.
对于同步测试,Jest 显示测试的路径(即file system › should check if the file exists
)这有助于追踪失败测试的根源。
对于异步测试来说,实现这一点的最佳方法是什么?