我正在尝试编写我的第一个jest测试,它将测试数据库调用。但我无法进行基本的mongo测试。
这是我的包.json
{
"scripts": {
"test": "jest"
},
"devDependencies": {
"@shelf/jest-mongodb": "^2.1.0",
"jest": "^27.2.4"
},
"dependencies": {
"mongodb": "^4.1.4"
},
"jest": {
"preset": "@shelf/jest-mongodb"
}
}
我去了https://jestjs.io/docs/mongodb并抓取这个例子粘贴到db.test.js
中
const {MongoClient} = require('mongodb');
describe('insert', () => {
let connection;
let db;
beforeAll(async () => {
connection = await MongoClient.connect(global.__MONGO_URI__, {
useNewUrlParser: true,
});
db = await connection.db(global.__MONGO_DB_NAME__);
});
afterAll(async () => {
await connection.close();
await db.close();
});
it('should insert a doc into collection', async () => {
const users = db.collection('users');
const mockUser = {_id: 'some-user-id', name: 'John'};
await users.insertOne(mockUser);
const insertedUser = await users.findOne({_id: 'some-user-id'});
expect(insertedUser).toEqual(mockUser);
});
});
然后我运行了以下命令:
npm install
npm run test
我得到了这些错误:
FAIL ./db.test.js
● insert › should insert a doc into collection
TypeError: Cannot read properties of undefined (reading 'match')
6 |
7 | beforeAll(async () => {
> 8 | connection = await MongoClient.connect(global.__MONGO_URI__, {
| ^
9 | useNewUrlParser: true,
10 | });
11 | db = await connection.db(global.__MONGO_DB_NAME__);
at new ConnectionString (node_modules/mongodb-connection-string-url/src/index.ts:98:23)
at parseOptions (node_modules/mongodb/src/connection_string.ts:249:15)
at new MongoClient (node_modules/mongodb/src/mongo_client.ts:327:34)
at Function.connect (node_modules/mongodb/src/mongo_client.ts:507:27)
at db.test.js:8:36
● Test suite failed to run
TypeError: Cannot read properties of undefined (reading 'close')
13 |
14 | afterAll(async () => {
> 15 | await connection.close();
| ^
16 | await db.close();
17 | });
18 |
at db.test.js:15:22
好像jest无法创建mongo实例?我做错了什么?
哦,我想明白了。这是我的最终解决方案:
我的包.json
{
"scripts": {
"test": "jest"
},
"devDependencies": {
"@shelf/jest-mongodb": "^2.1.0",
"jest": "^27.2.4"
}
}
我还需要一个jest.config.js
,它看起来像这样:
module.exports = {
preset: '@shelf/jest-mongodb',
};
由给出的示例测试https://jestjs.io/docs/mongodb是有缺陷的。所以我在db.test.js中修复了它,现在看起来像这样:
const {MongoClient} = require('mongodb');
describe('insert', () => {
let connection;
let db;
beforeAll(async () => {
connection = await MongoClient.connect(global.__MONGO_URI__, {
useNewUrlParser: true,
});
db = await connection.db(global.__MONGO_DB_NAME__);
});
afterAll(async () => {
await connection.close();
if(db.close) {
await db.close();
}
});
it('should insert a doc into collection', async () => {
const users = db.collection('users');
const mockUser = {_id: 'some-user-id', name: 'John'};
await users.insertOne(mockUser);
const insertedUser = await users.findOne({_id: 'some-user-id'});
expect(insertedUser).toEqual(mockUser);
});
});
然后我运行了npm install; npm run test;
。我看到了测试运行并取得了成功。