Skip to main content

How to use Assert in MochaJS

In this article I show how to use assert to test if something is true or false in MochaJS.

Step 1. Initialize a new test project

Create a test project folder and initialize it with npm.

If you need more details on these steps, see my article on MochaJS setup.

On a Mac or Linux machine, open up a terminal window and do the following:

mkdir mocha-assert
cd mocha-assert
npm init -y

Step 2. Add the mochajs package

npm install --save-dev mocha

Step 3. Add a test script to package.json

Add an npm script entry to run mocha:

  • Edit package.json

  • Update the scripts/test section of package.json to call mocha:

    "scripts": {
    "test": "mocha"
    },
  • Save the file

Step 4. Create a source folder

In the root of your project create a folder called src.

mkdir src

Step 5. Define a module to test

Create a file in the src folder called index.js

On a Mac you can initialize an empty file like this:

touch src/index.js

For testing, define a pet base class and derive a dog and a cat class.

Paste the following into src/index.js and save the file.

// define a pet base class

class Pet {
constructor(brand, sound) {
this.petType = brand;
this.sound = sound;
}

speak() {
console.log( this.petType + " goes " + this.sound );
}
}

// derive a dog class from the pet class

class Dog extends Pet {
constructor() {
super('dog','woof');
}
}

// derive a cat class from the pet class

class Cat extends Pet {
constructor() {
super('cat','meow');
}
}

// define factory functions

function createDog() {
return new Dog();
}

function createCat() {
return new Cat();
}

// export the factory functions

module.exports = {
createDog,
createCat,
}

The base class

The Pet base class has a constructor that can be passed two properties: petType and sound.

It also has one method named speak. The method prints a sentence that displays the petType and sound values.

The derived classes

The Dog and Cat classes are derived from the Pet base class. Their constructors call the base class constructor to set the petType and sound properties.

The factory functions

The createDog and createCat functions are what is known as factory functions. They hide the details of creating new objects and can be called with no parameters.

The exported functions

The two factory functions are wrapped in module.exports. That is so they can be used by an other file that requires the source file.

Step 6. Create a test folder

By default, MochaJS will look for test files in a subfolder called test.

mkdir test

Step 7. Create a test file

Add a new test file to the test folder.

touch test/smoke-test.js

Step 6. Define tests using assert.ok

Paste the contents below into test/smoke-test.js and save the file:

"use strict";

// require assert

var assert = require('assert');

// require the pet module

const petFactory = require('../src');

describe('smoke test', function() {
context('createDog', function() {
// factory method
it('should return an object that is not null', function(done) {
var dog = petFactory.createDog();
assert.ok(dog, 'dog should not be null');
done();
});
// properties and methods on object exist
it('should return an object with a petType property', function(done) {
var dog = petFactory.createDog();
assert.ok(dog.petType, 'dog should have a petType property');
done();
});
it('should return an object with a sound property', function(done) {
var dog = petFactory.createDog();
assert.ok(dog.sound, 'dog should have a sound property');
done();
});
it('should return an object with a speak method', function(done) {
var dog = petFactory.createDog();
assert.ok(dog.speak, 'dog should have a speak method');
done();
});
});
});

The tests above all use the assert.ok method to test if an object, property or method exists. If any of them are null an error will occur.

Why didn’t assert need to be installed?

You may be wondering why assert didn’t need to be installed as a package. That’s because it is built in to NodeJS and always available.

Step 7. Run the assert.ok tests

To run the tests from the command line:

npm test

You should see output like this:

  smoke test
createDog
✓ should return an object that is not null
✓ should return an object with a petType property
✓ should return an object with a sound property
✓ should return an object with a speak method

4 passing (9ms)

Step 8. Break a test

To see what a fail looks like, change a line in the last test.

Make .speak .speakX, save the file and rerun the tests:

assert.ok(dog.speakX, 'dog should have a speak method');

You should see an output like this:

  smoke test
createDog
✓ should return an object that is not null
✓ should return an object with a petType property
✓ should return an object with a sound property
1) should return an object with a speak method

3 passing (15ms)
1 failing

1) smoke test
createDog
should return an object with a speak method:
AssertionError [ERR_ASSERTION]: dog should have a speak method
at Context.<anonymous> (test/smoke-test.js:32:11)
at processImmediate (internal/timers.js:456:21)

Fix the error and run it again to make sure everything passes.

Step 9. Add assert.equal tests

Add two tests that use assert.equal and save the file.

// property values
it('should return an object where petType is dog', function(done) {
var dog = petFactory.createDog();
assert.equal( dog.petType, 'dog', 'petType should be dog');
done();
});
it('should return an object where sound is woof', function(done) {
var dog = petFactory.createDog();
assert.equal( dog.sound, 'woof', 'sound should be woof');
done();
});

The tests verify that dog.petType equals dog and that dog.sound equals woof.

Step 10. Run the assert.equal tests

Run the tests from the command line:

npm test

You should see output like this:

  smoke test
createDog
✓ should return an object that is not null
✓ should return an object with a petType property
✓ should return an object with a sound property
✓ should return an object with a speak method
✓ should return an object where petType is dog
✓ should return an object where sound is woof

6 passing (11ms)

Troubleshooting

A simple way to debug issues is to log what a factory method is actually returning. To do that in a test, add a console.log line.

Here is an example:

it('should return an object where sound is woof', function(done) {
var dog = petFactory.createDog();
console.log(dog);
assert.equal( dog.sound, 'woof', 'sound should be woof');
done();
});

When you run the tests, the output would contain the log line:

  smoke test
createDog
✓ should return an object that is not null
✓ should return an object with a petType property
✓ should return an object with a sound property
✓ should return an object with a speak method
✓ should return an object where petType is dog
Dog { petType: 'dog', sound: 'woof' }
✓ should return an object where sound is woof

In general you only want to do that when debugging a test. Then comment out the console.log line. Otherwise it will make the test results difficult to read.

Conclusion

In this article I introduced you to the NodeJS built in assert libary.

You learned how do do the following:

  • Incude the assert library in your tests
  • Use the assert.ok method to test if an object or property is null
  • Use the assert.equal method to test if a property is the expected value

That is only some of what the assert libary can do. For other functionality, refer to the documentation which can be found here.

Exercise for the reader

An excercise for the reader is to add tests for the cat factory method.

References

  • nodejs.org/api/assert.html [1]