Test Driven Development - Mocha Intro

How-To Reference

Building Tests

This MongoDB class is having a lot more benefit than expected. Before even getting into building an app, we’ve learned how to build tests using Mocha to assert what the results of a given action should be. For example, to test delete actions:

const assert = require("assert");
const User = require("../src/user");

describe("Remove/destroy a user", () => {
let joe;

beforeEach((done) => {
joe = new User({ name: "Joe" });
joe.save()
.then(() => done());
});

it("removes a model instance", (done) => {
// Chain promises so that you remove the user, when that's done search for the user,
// and when that's done run the test to see if the user exists
joe.remove()
.then(() => User.findOne({ name: "Joe" }))
.then((user) => {
assert(user === null);
done();
});
});

it("removes a class method", (done) => {
// Remove a bunch of records with some given criteria
User.remove({ name: "Joe" })
.then(() => User.findOne({ name: "Joe" }))
.then((user) => {
assert(user === null);
done();
});
});

it("removes a class findOneAndRemove method", (done) => {
User.findOneAndRemove({ name: "Joe" })
.then(() => User.findOne({ name: "Joe" }))
.then((user) => {
assert(user === null);
done();
});
});

it("removes a class findByIdAndRemove method", (done) => {
User.findByIdAndRemove(joe._id)
.then(() => User.findOne({ name: "Joe" }))
.then((user) => {
assert(user === null);
done();
});
});
});

Mongo Update Modifiers

I also learned that there are built-in functions in Mongo which do exactly the things I need to know how to do for my app. Yay!

Up Next

This stuff is really fun and I can totally anticipate getting sidetracked and not finishing CS50 in time. So I’ve gotta go back to that!