【发布时间】:2022-08-07 21:28:59
【问题描述】:
在运行我的测试时,我试图摆脱笑话消息“Jest has detected the following 2 open handles”。但我现在已经走到了死胡同。
这是我试图修复的测试之一:
describe(\'POST /products\', function () {
let agent, server
beforeEach(function (done) {
server = app.listen(3001, (err) => {
if (err) return done(err);
agent = supertest(server)
done();
})
utils.reset()
})
it(\'Adds a new product\', function () {
utils.testCategories().push(\'Celulares\') // This function returns an array of strings
return agent
.post(\'/products\')
.send({
name: \'iPhone 13 Pro\',
brand: \'Apple\',
category: \'Celulares\',
stock: 8
})
.expect(201)
.expect(\'Content-Type\', /json/)
.expect(function (res) {
expect(res.body).toEqual({
name: \'iPhone 13 Pro\',
categoryId: 1,
brand: \'Apple\',
stock: 8,
available: true,
reviews: [],
rating: 0
})
expect(utils.testProducts()).toHaveLength(1) // This one an array of objects
expect(utils.testProducts()[0].name).toEqual(\'iPhone 13 Pro\')
})
afterEach((done) => {
server.close(done)
})
})
})
我没有看到该代码有任何问题,我打开服务器,然后关闭它。
这是我尝试测试的路线:
router.post(\'/products\', async (req, res) => {
const { name, brand, category, stock } = req.body;
addProduct(name, brand, category, stock) // This function makes an async operation with a fake db
.then((results) => {
res.status(201).send(results)
})
.catch(err => res.status(404).send({ error: err.message }))
})
测试完成后,jest 在控制台上打印此消息
Jest has detected the following 1 open handle potentially keeping Jest from exiting:
● bound-anonymous-fn
6 | let agent, server
7 | beforeEach(function (done) {
> 8 | server = app.listen(3001, (err) => {
| ^
9 | if (err) return done(err);
10 | agent = supertest(server)
11 | done();
at Function.listen (node_modules/express/lib/application.js:635:24)
at Object.<anonymous> (tests/11.test.js:8:18)
at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/@jest/core/build/runJest.js:404:19)
at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7)
at runCLI (node_modules/@jest/core/build/cli/index.js:173:3)
也许值得注意的是,在 GET 请求中,这条消息根本没有这个问题。
另外,我在执行测试时尝试过使用 --forceExit ,但这不是一个合适的解决方案,它实际上一直在打印消息。
任何提供的建议将不胜感激
标签: javascript node.js express jestjs supertest