Let's work with a test suite that I wrote to help make sure that our MongoDB connection is a bit more robust and includes inserting data into the database and then testing to be sure it exists:
- Examine test/setup.model.test.js:
const MongoDB = require('../models/mongo')
const insertRandomNames = require('../models/setup')
describe('insert', () => {
let db
beforeAll(async () => {
db = await MongoDB.connectDB('test')
})
afterAll(async (done) => {
await db.collection('names').deleteMany({})
await MongoDB.disconnectDB()
done()
})
it('should insert the random names', async () => {
await insertRandomNames()
const names = await db.collection("names").find().toArray()
expect(names.length).toBeGreaterThan(0)
})
})
- If we run node_modules/.bin/jest setup, we'll see success because the insertRandomNames() method exists from our setup model. So let's take a look...