I am trying to test basic mongoDB operation using Jest.
it('should insert a record into collection', async () => {
const users = await db.collection('mariochar');
const mockUser = { name: 'marioChar3'};
await users.insertOne(mockUser);
const insertedUser = await users.findOne({name: 'marioChar3'});
expect(insertedUser).toEqual(mockUser);
});
If I use the default Jest suggested template as above, tests are passing correctly and records can also be seen in the database.
However, since I was learning from this youtube tutorial, I tried to test the Schema directly as shown in the video like this:
it('should insert a mario into collection', async () => {
const MarioCharSchema = new Schema({
name: String,
weight: Number
})
const MarioChar = await mongoose.model('mariochar', MarioCharSchema)
const char = await new MarioChar({ name: "Mario" })
char.save()
console.log(char.isNew)
expect(char.isNew).toBeTruthy()
});
I get the error: ReferenceError: You are trying toimporta file after the Jest environment has been torn down.
After viewing few posts in stackoverflow, I added the fake timer and I am posting the complete code below. It did not get rid of the error.
My second question is that even though Jest shows the above error and also npm ERR! Test failed. See above for more details., it shows the test as passed. Is there a way to report it as failed instead since it is easy to mistake it as passed when there will be a lot of tests?
const { MongoClient } = require('mongodb');
const mongoose = require('mongoose')
const Schema = mongoose.Schema
jest.useFakeTimers()
describe('insert', () => {
let connection;
let db;
beforeAll(async () => {
jest.useFakeTimers()
connection = await MongoClient.connect("mongodb://localhost/testaroo", {
useNewUrlParser: true,
useUnifiedTopology: true
});
db = await connection.db();
});
afterAll(async () => {
await connection.close();
});
it('should insert a mario into collection', async () => {
const MarioCharSchema = new Schema({
name: String,
weight: Number
})
const MarioChar = await mongoose.model('mariochar', MarioCharSchema)
const char = await new MarioChar({ name: "Mario" })
char.save()
expect(char.isNew).toBeTruthy()
});
});
jest.config.js
module.exports = {
"preset": '@shelf/jest-mongodb',
"timers": "fake",
"testEnvironment": "node"
};
package.json
...
"dependencies": {
"mongoose": "^5.9.18"
},
"devDependencies": {
"@shelf/jest-mongodb": "^1.1.5",
"jest": "^26.0.1"
}
...
full error:
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
at model.Document.$__getAllSubdocs (node_modules/mongoose/lib/document.js:2890:37)
at _getPathsToValidate (node_modules/mongoose/lib/document.js:2159:23)
at model.Document.$__validate (node_modules/mongoose/lib/document.js:2314:23)
at node_modules/kareem/index.js:369:33
at node_modules/@jest/fake-timers/build/legacyFakeTimers.js:496:18
PASS test/saving.test.js