使用Express完成测试运行后,Jest没有退出一秒钟

时间:2018-12-26 17:22:43

标签: typescript unit-testing express jestjs

我正在使用JEST对我的快递路线进行单元测试。

运行yarn test的所有测试用例都通过了,但出现错误

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

我使用了asyncdone,但仍然会引发上述错误。

以下是我的规范代码。请帮助

routes.spec.ts

const request = require('supertest');
describe('Test the root path', () => {
  const app = require('./index');

  test('GET /gql/gql-communication-portal/release-notes', async (done) => {
    const response = await request(app).get('/gql/gql-communication-portal/release-notes');
    expect(response.status).toBe(200);
    done();
  });
});

5 个答案:

答案 0 :(得分:2)

对我来说,这是另一个问题,我使用超级测试来测试路由本身,因此必须关闭与服务器本身的连接。

afterAll(done => {
    server.close();
    done();
});

如果不是您这种情况,this issue可能会为您提供一些东西

答案 1 :(得分:2)

在我这边,我只是将app.listen()与应用程序分开了。 因此,借助express,您的应用程序将以导出完成。

// index.js
module.exports = app;

然后创建另一个文件来监听端口。

// server.js
const app = require('./index')
app.listen(...)

如果在测试中仅导入索引(应用index.js),则该索引无需额外配置即可工作。 当然,您需要调整Express应用程序的启动。现在应该使用server.js

答案 2 :(得分:0)

我遇到了同样的问题,但是在我的package.json文件中添加了“ test”:“ jest --detectOpenHandles”并运行了npm test --detectOpenHandles。这次我没有收到错误消息。也许您可以尝试这样做。

答案 3 :(得分:0)

我的问题已通过以下代码解决:

beforeAll(done => {
  done()
})

afterAll(done => {
  // Closing the DB connection allows Jest to exit successfully.
  mongoose.connection.close()
  done()
})

答案 4 :(得分:0)

这对我有用

const mongoose = require('mongoose');
    afterAll(async(done) => {
  // Closing the DB connection allows Jest to exit successfully.
  try {
    await mongoose.connection.close();
    done()
  } catch (error) {
    console.log(error);
    done()
  }
  // done()
})