测试失败后,Jest globalTeardown无法运行

时间:2020-01-18 20:31:27

标签: node.js testing jestjs

我正在尝试通过代码启动和停止无服务器应用程序。一旦所有测试通过,我就能启动和停止它。但是,如果测试失败globalTeardown,请不要运行。您可以在此处检查示例项目:https://github.com/bilalsha/sls-test-jest/tree/fail_test

teardown.js

module.exports = async function() {
    let slsOfflineProcess = global.__SERVERD__;
    slsOfflineProcess.stdin.write('q\n');
    slsOfflineProcess.stdin.pause();
    await slsOfflineProcess.kill('SIGINT');
    console.log('Serverless Offline stopped');
};

output

      7 |              expect(res.statusCode).toEqual(200);
    >  8 |              expect(res.body).toEqual('Go Serverless v1.0! Your function executed successfully!');
         |                               ^
       9 |      });
      10 | });
      11 | 

      at Object.<anonymous> (handler.test.js:8:20)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        1.972s, estimated 2s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

2 个答案:

答案 0 :(得分:2)

仅将文档设置为bail: true时,jest.config.js中就出现问题了

https://github.com/bilalsha/sls-test-jest/blob/fail_test/test/jest.config.js#L3

文档说,如果保释金为真,则与在第一次失败后停止测试相同。

https://jestjs.io/docs/en/configuration#bail-number--boolean

我会尝试更改bail: 0(默认设置),并查看它是否产生了预期的行为。

答案 1 :(得分:1)

您可以做的就是添加一个包含afterAll函数的脚本:

afterAll(() => {
  console.log("I ran");
});

并将脚本添加到setupFilessetupFilesAfterEnv。就我而言,我弹出了一个测试失败的react poc代码:

package.json的Jest配置中,存在以下条目:

"jest": {
    ...
    "setupFilesAfterEnv": [
      "<rootDir>/src/setupTests.js"
    ],
    ...
}

因此,我在下面的setupTests.js中添加了该子句:

// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';

afterAll(() => {
  console.log("I ran");
});

现在,当我运行测试时,结果如下:

 FAIL  src/App.test.js
  ✓ renders learn react link (14ms)
  ✕ renders class (5ms)

  ● renders class

    expect(jest.fn()).toHaveBeenCalledTimes(expected)

    Expected number of calls: 1
    Received number of calls: 0

      18 |   // someClass.someProp = "";
      19 |   render(<App />);
    > 20 |   expect(track).toHaveBeenCalledTimes(1);
         |                 ^
      21 | });
      22 | 

      at Object.<anonymous> (src/App.test.js:20:17)

  console.log src/setupTests.js:8
    I ran <---------------

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.352s, estimated 2s
Ran all test suites.

即使测试失败,您仍可以看到I ran在那。这是您可以使用的替代方法,因为您已经悬赏金了,我认为也许解决问题比为什么globalTeardown不起作用更为重要。