Beginner’s Guide To Writing MongoDB/Mongoose Unit Tests Using Mocha/Chai

Mike (Nongaap)
nongaap
Published in
2 min readSep 2, 2016

Summary: Basic introduction to writing MongoDB unit tests using Mocha/Chai. (Sample test file below)

Prerequisite: This post assumes you have a basic understanding of MongoDB, Node.js, and Mocha, and have them installed on your computer. You should also have Mongoose and Chai NPM installed.

Testing is really important.

When speaking to experienced software developers, a recurring theme new software developers will consistently hear is the importance of writing unit tests. Proponents of Test Driven Development will highlight how writing your unit tests first will actually make your code base much more modular long-term, produce cleaner — daresay pure — functions, and forces a developer to think through the problem they are trying to solve at a high level.

I personally think there’s a much simpler reason why new developers should write unit tests.

Eventually you’re going to break your codebase and you will need a fast and efficient way to debug your code and effectively integrate your work within a team setting.

Further, writing unit tests becomes a great way to learn new, more technical parts of the stack. I found writing unit tests a great way to deconstruct new tech and really helped me figure out what it does.

When I was first exposed to MongoDB and Mongoose schemas, I found unit test a phenomenal way of learning how to implement it.

Below is a copy of some test code I wrote when first learning MongoDB/Mongoose along with comments I wrote to walk through my thinking.

"use strict";// NPM install mongoose and chai. Make sure mocha is globally
// installed
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const chai = require('chai');
const expect = chai.expect;
// Create a new schema that accepts a 'name' object.
// 'name' is a required field
const testSchema = new Schema({
name: { type: String, required: true }
});
//Create a new collection called 'Name'
const Name = mongoose.model('Name', testSchema);
describe('Database Tests', function() {
//Before starting the test, create a sandboxed database connection
//Once a connection is established invoke done()
before(function (done) {
mongoose.connect('mongodb://localhost/testDatabase');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', function() {
console.log('We are connected to test database!');
done();
});
});
describe('Test Database', function() {
//Save object with 'name' value of 'Mike"
it('New name saved to test database', function(done) {
var testName = Name({
name: 'Mike'
});

testName.save(done);
});
it('Dont save incorrect format to database', function(done) {
//Attempt to save with wrong info. An error should trigger
var wrongSave = Name({
notName: 'Not Mike'
});
wrongSave.save(err => {
if(err) { return done(); }
throw new Error('Should generate error!');
});
});
it('Should retrieve data from test database', function(done) {
//Look up the 'Mike' object previously saved.
Name.find({name: 'Mike'}, (err, name) => {
if(err) {throw err;}
if(name.length === 0) {throw new Error('No data!');}
done();
});
});
});
//After all tests are finished drop database and close connection
after(function(done){
mongoose.connection.db.dropDatabase(function(){
mongoose.connection.close(done);
});
});
});

--

--

Mike (Nongaap)
nongaap

Ex-Activist Investor. Ex-JavaScripter. Current: http://nongaap.substack.com. Mostly tweet about tech, governance, strategy, board dynamics, & art of corp war.