【问题标题】:How to fix err Jest has detected the following 3 open handles potentially keeping Jest from exiting如何修复错误 Jest 检测到以下 3 个打开的句柄可能会阻止 Jest 退出
【发布时间】:2018-06-12 13:23:57
【问题描述】:

刚开始使用 jest 测试一些节点应用程序。 express-generator 用于脚手架。
在第一次测试中,我收到以下错误:

Jest 检测到以下 3 个打开的句柄可能会阻止 Jest 退出

重现步骤:

git clone git@github.com:gandra/node-jest-err-demo.git   
cd node-jest-err-demo       
npm install   
cp .env.example .env    
npm run test  

npx envinfo --preset jest 输出:

npx: installed 1 in 1.896s

  System:
    OS: macOS High Sierra 10.13.4
    CPU: x64 Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz   Binaries:
    Node: 9.3.0 - /usr/local/bin/node
    Yarn: 1.5.1 - /usr/local/bin/yarn
    npm: 5.7.1 - /usr/local/bin/npm   npmPackages:
    jest: ^23.1.0 => 23.1.0

知道怎么解决吗?

这里是github上的相关问题:https://github.com/facebook/jest/issues/6446

【问题讨论】:

  • 这不是真正的问题,而是预期的行为。我想这里真正的问题是process.env.NODE_ENV 不是test,我建议重写问题以反映这一点。

标签: node.js tdd jestjs


【解决方案1】:

这是我为解决这个问题所做的。

    afterAll(async () => {
  await new Promise(resolve => setTimeout(() => resolve(), 10000)); // avoid jest open handle error
});

然后我在给出问题的特定测试中设置 jest.setTimeout。

describe('POST /customers', () => {
  jest.setTimeout(30000);
  test('It creates a customer', async () => {
    const r = Math.random()
      .toString(36)
      .substring(7);
    const response = await request(server)
      .post('/customers')
      .query({
        name: r,
        email: `${r}@${r}.com`,
        password: 'beautiful',
      });
    // console.log(response.body);
    expect(response.body).toHaveProperty('customer');
    expect(response.body).toHaveProperty('accessToken');
    expect(response.statusCode).toBe(200);
  });
});

如上所述,关闭所有其他打开的句柄。

【讨论】:

    【解决方案2】:

    detectOpenHandles 选项用于检测打开的句柄,应该正常使用。该错误警告可能打开句柄:

    Jest 检测到以下 4 个打开的句柄可能会阻止 Jest 退出

    即使将句柄关闭,错误仍然会出现。

    这个应用程序的实际问题是数据库连接并没有真正关闭:

    if (process.env.NODE_ENV === 'test') {
      mongoose.connection.close(function () {
        console.log('Mongoose connection disconnected');
      });
    }
    

    由于某种原因,NODE_ENVdev,尽管 the documentation 声明它应该是 test

    在应用程序启动时立即关闭数据库连接可能会导致实际使用数据库连接的单元出现问题。如指南中所述,MongoDB 连接应该在测试结束时。由于使用了默认的 Mongoose 连接,因此可以:

    afterAll(() => mongoose.disconnect());
    

    【讨论】:

      猜你喜欢
      • 2019-03-13
      • 2020-09-20
      • 2020-08-24
      • 2021-09-26
      • 1970-01-01
      • 2019-06-30
      • 2021-06-13
      • 2020-11-13
      • 2018-11-14
      相关资源
      最近更新 更多