为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Jest 中跟踪失败的异步测试?

如何在 Jest 中跟踪失败的异步测试?

qq_花开花谢_0 2023-05-11 16:12:48
问题已确定。在实际的代码库中,断言被传递给一个导入的回调,一旦回调执行失败的测试,它就会引发承诺拒绝。所以,这接近于测试的实际编写方式: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;}什么时候fileExists 拒绝退货false,UnhandledPromiseRejectionWarning收到不出所料. 但这无助于追踪失败测试的根源。对于同步测试,Jest 会显示测试路径(即file system › should check if the file exists),这有助于跟踪失败测试的来源。实现异步测试的最佳方法是什么?
查看完整描述

1 回答

?
茅侃侃

TA贡献1842条经验 获得超21个赞

UnhandledPromiseRejectionWarning预计不会在这里。它不等同于失败的测试,因为如果断言通过,它不会阻止测试通过。这意味着代码以错误的方式编写并且包含不受限制的承诺。


await它只有在测试中被省略时才会发生:


fileExists(); // no await

或者fileExists函数包含松散的未处理的承诺:


fileExists() {

  whatever() // no return

  .then(() => {

    whatever() // no return

  })  // no catch to suppress errors

}

这是一个很好的做法setupFiles:


process.on('unhandledRejection', console.error);

它提供比UnhandledPromiseRejectionWarning错误堆栈更有用的输出并允许调试问题。


查看完整回答
反对 回复 2023-05-11
  • 1 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信