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



这是我的HTTP路由

app.get('/', (req, res) => {
res.status(200).send('Hello World!')
})
app.post('/sample', (req, res) => {
res.status(200).json({
x:1,y:2
});
})

我想测试以下内容

1(GET请求工作正常。

2(/sample响应包含属性和xy

const request = require('supertest');
const app = require('../app');
describe('Test the root path', () => {
test('It should response the GET method', () => {
return request(app).get('/').expect(200);
});
})
describe('Test the post path', () => {
test('It should response the POST method', (done) => {
return request(app).post('/sample').expect(200).end(err,data=>{
expect(data.body.x).toEqual('1');
});
});
})

但是我在运行测试时遇到以下错误

Jest 检测到以下 1 个打开的句柄可能使 Jest 保持 从退出:

return request(app(.get('/'(.expect(200(;

你需要在end()方法中调用done()

const request = require("supertest");
const app = require("../app");
let server = request(app);
it("should return 404", done =>
server
.get("/")
.expect(404)
.end(done);
});

这个技巧奏效了;

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

如本 github 问题中所述。

嗨,您也可以使用 toEqual 函数

describe('Test the post path', () => {
test('It should response the POST method', () => {
return request(app).post('/sample').expect(200).toEqual({ x:1,y:2
});
});
})

可以使用很多方法代替。你可以去扔官方文档,其中涵盖了每个开玩笑的功能 https://jestjs.io/docs/en/expect

作为调试此错误的一般提示,请将--detectOpenHandles添加到运行 Jest 的 npm 脚本中,例如

"scripts": {
...
"test": "jest --detectOpenHandles"
}

这应该确切地告诉您代码的哪一部分导致了问题(可能是某种类型的服务器连接,特别是如果它async(。

通常,如果可以将连接代码移动到测试之外的文件中的单独函数,然后在测试中导入并调用它,这也将解决问题。

最新更新