代码之家  ›  专栏  ›  技术社区  ›  Vince Varga

如何确保Jest在“unhandledrepression”上失败?

  •  1
  • Vince Varga  · 技术社区  · 8 年前

    有时,我们不处理单元测试中的拒绝,但是,我认为这是不正确的,在我看来,管道应该失败。

    jest unhandledRejection

    我试图在安装脚本中钩住事件侦听器:

    /* jest.config.js */
    module.exports = {
        setupFiles: ['<rootDir>/test/setup.ts'],
        // ...
    }
    

    在安装脚本中,我可以检测到 但不幸的是,我不能开玩笑

    process.on('unhandledRejection', () => {
        console.error('Now what?');
        console.error('I want to make sure that jest exits with an error!');
    });
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Andrew Eisenberg    6 年前

    可以创建jest配置文件 jest.config.js 并将以下条目放入其中:

    module.exports = {
      ...
      setupFiles: ['<rootDir>/test/setup.js'],
      ...
    };
    

    然后在你的 setup.js

    process.on('unhandledRejection', (err) => {
      fail(err);
    });
    

    unhandledRejection 将无法通过测试,但有两个注意事项:

    1. 来自承诺的未处理拒绝,当新测试运行时拒绝的承诺(不是启动承诺的承诺)将使新测试失败,而不是原始测试失败。这是令人困惑的,并可能使跟踪错误变得困难。

        2
  •  0
  •   goonieiam    8 年前

    --detectOpenHandles --forceExit --runInBand