![](/img/trans.png)
[英]Testing Express, MongoDB & TypeScript with supertest and Jest fails when I use app
[英]Teardown Errors when testing with Jest, Supertest, MongoDB, and Express
我正在使用 Jest 和 Supertest 測試我的 Express 路線。 在設置應用程序時,我還連接到 MongoDB 並將 MongoClient 添加到app.locals
。
我收到一個錯誤,當我注釋掉對 MongoClient 的調用時,該錯誤不會發生。
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
at BufferList.Readable (server/node_modules/readable-stream/lib/_stream_readable.js:179:22)
at BufferList.Duplex (server/node_modules/readable-stream/lib/_stream_duplex.js:67:12)
at new BufferList (server/node_modules/bl/bl.js:33:16)
at new MessageStream (server/node_modules/mongodb/lib/cmap/message_stream.js:35:21)
at new Connection (server/node_modules/mongodb/lib/cmap/connection.js:54:28)
/Users/zackchan/Documents/dev/server/node_modules/readable-stream/lib/_stream_readable.js:111
var isDuplex = stream instanceof Duplex;
^
TypeError: Right-hand side of 'instanceof' is not callable
at new ReadableState (/Users/zackchan/Documents/dev/server/node_modules/readable-stream/lib/_stream_readable.js:111:25)
at BufferList.Readable (/Users/zackchan/Documents/dev/server/node_modules/readable-stream/lib/_stream_readable.js:183:25)
at BufferList.Duplex (/Users/zackchan/Documents/dev/server/node_modules/readable-stream/lib/_stream_duplex.js:67:12)
at new BufferList (/Users/zackchan/Documents/dev/server/node_modules/bl/bl.js:33:16)
at new MessageStream (/Users/zackchan/Documents/dev/server/node_modules/mongodb/lib/cmap/message_stream.js:35:21)
at new Connection (/Users/zackchan/Documents/dev/server/node_modules/mongodb/lib/cmap/connection.js:54:28)
at /Users/zackchan/Documents/dev/server/node_modules/mongodb/lib/core/connection/connect.js:36:29
at callback (/Users/zackchan/Documents/dev/server/node_modules/mongodb/lib/core/connection/connect.js:280:5)
at TLSSocket.connectHandler (/Users/zackchan/Documents/dev/server/node_modules/mongodb/lib/core/connection/connect.js:325:5)
at Object.onceWrapper (events.js:421:28)
當我注釋掉我的 MongoClient 調用時,我收到了這個 Jest 警告:
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.
這是我的測試腳本和應用程序模塊
應用程序.js
const https = require('https');
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
const express = require('express');
const rateLimiter = require('express-rate-limit');
const { MongoClient } = require('mongodb');
const app = express();
const port = process.env.PORT || 443;
const limit = rateLimiter({ window: 15 * 60 * 1000, max: 100 });
var httpsOptions;
if(process.env.NODE_ENV === 'development'){
const rootCA = require('ssl-root-cas').create().addFile(path.join(__dirname, './cert/CA.pem'));
https.globalAgent.options.ca = rootCA;
httpsOptions = {
key: fs.readFileSync(path.join(__dirname, './cert/localhost.key')),
cert: fs.readFileSync(path.join(__dirname, './cert/localhost.crt'))
};
}
MongoClient.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true }, (err, mongoClient) => {
if(err) throw err;
app.locals.mongoClient = mongoClient;
});
app.use(limit);
app.use(express.json());
app.get('/', (req, res) => {
res.json({path: '/'});
});
const server = https.createServer(httpsOptions, app).listen(port);
module.exports = app;
測試.js
const dotenv = require('dotenv');
const path = require('path');
process.env = dotenv.config({path: path.resolve(__dirname, '.env')}).parsed;
const request = require('supertest');
const app = require('../app');
describe('GET /', () => {
it('responds with path of /', (done) => {
// app.locals is empty here
request(app).get('/').expect(JSON.stringify({path: '/'}), done);
});
});
我嘗試在測試用例后使用app.locals.mongoClient.close()
關閉與 MongoDB 的連接,但此處未定義mongoClient
。 我還嘗試將MongoClient.connect()
調用包裝在異步 function 中,然后調用它,但這也無濟於事。
有人對我應該嘗試什么有想法嗎?
我通過以下方式解決了這個問題:
app.locals
文件中的test.js
,您仍然可以通過req.app.locals
訪問 MongoDB 連接。app.js
中封裝了我的MongoClient.connect()
調用:if(process.env.NODE_ENV === 'production'){
MongoClient.connect(...)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.