[英]Jest + Supertest | Jest detecting open handles
在運行我的測試時,我試圖擺脫開玩笑的消息“Jest 檢測到以下 2 個打開的句柄”。 但我現在已經走到了死胡同。
這是我試圖修復的測試之一:
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 ,但這不是一個合適的解決方案,它實際上一直在打印消息。
任何提供的建議將不勝感激
看起來這已在最近的更新中得到修復,升級到jest@29.2.1
和ts-jest@29.0.3
為我解決了這個問題。
我遇到了同樣的情況。
我不知道問題/原因是什么 - 但在 github 的 jest 存儲庫中可以看到更多信息(也許還有 supertest)。
我降級了我的軟件包: npm i jest@26.6.3 ts-jest@26.5.6 -D
,以前我有"jest": "^27.5.1",
和"ts-jest": "^27.1.4",
. 使用26.xx
的 jest/ts-jest 版本,我不再面臨警告。
我根據此評論進行了降級: https://github.com/facebook/jest/issues/11649#issuecomment-992690198
僅供參考,如果您還在 Express 應用程序上使用body-parser
,那么有一個活躍的錯誤也會導致此問題: https://github.com/ladjs/supertest/issues/772
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.