Aw3*_*Sol 33 unit-testing express typescript 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.
Run Code Online (Sandbox Code Playgroud)
我使用了async& done,但它仍然抛出上述错误。
下面是我的规范代码。请帮忙
路线.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();
});
});
Run Code Online (Sandbox Code Playgroud)
Sal*_*deh 44
My problem was solved by this code:
beforeAll(done => {
done()
})
afterAll(done => {
// Closing the DB connection allows Jest to exit successfully.
mongoose.connection.close()
done()
})
Run Code Online (Sandbox Code Playgroud)
小智 31
我已将此行添加到 package.json
这对我有用
jest --runInBand --detectOpenHandles --forceExit
Run Code Online (Sandbox Code Playgroud)
aqu*_*inq 13
添加
jest.useFakeTimers();
Run Code Online (Sandbox Code Playgroud)
在测试套件开始时为我修复了它。
可能来自渲染组件部分中定义的计时器(如节流按钮、模拟等)。
小智 11
我遇到了同样的问题,但在我的 package.json 文件中添加"test": "jest --detectOpenHandles"并运行了npm test --detectOpenHandles。这次我没有收到错误消息。也许你可以尝试这样做。
这对我有用
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()
})
Run Code Online (Sandbox Code Playgroud)
在我这边,我只是与app.listen()我的应用程序分开。因此,使用 express,您的应用程序以导出完成。
// index.js
module.exports = app;
Run Code Online (Sandbox Code Playgroud)
只需创建另一个文件来监听端口。
// server.js
const app = require('./index')
app.listen(...)
Run Code Online (Sandbox Code Playgroud)
如果您index.js在测试中只导入索引 (app ),它应该无需额外配置即可工作。当然,您需要调整快递应用程序的启动。它现在应该使用server.js.
对我来说,这是一个不同的问题,我使用 supertest 来测试路由本身,所以我不得不关闭与服务器本身的连接。
afterAll(done => {
server.close();
done();
});
Run Code Online (Sandbox Code Playgroud)
如果您不是这种情况,则此问题可能对您有所帮助
| 归档时间: |
|
| 查看次数: |
39553 次 |
| 最近记录: |