Mocha Setup

To do unit testing on the server side is very similat to using Mocha in the browser. The actual Mocha setup is actually less, but you do need to create and import modules for you functions and tests.

You will need to move code you wrote in the bootcamp into files in a directory on your PC and ensure each file is a module that can be imported. Use the bootcamp-backend-tests folder in your projects folder.

Read more here to configure Mocha. You will use NodeJS’s built in assert module to do asserts.

Start by moving the greet function for the first bootcamp exercise into a greet.js file.

And make it a NodeJS module like this:

module.exports = function(name){
    return "Hello, " + name;
}

For NodeJS to have access to the functions to be tested need to imported using the require statement. Mocha looks for tests in your project folder in a folder called test. Be sure to create your test in the test folder in a file called greet.tests.js.

Install Mocha

You need to install Mocha using this command:

sudo npm install -g mocha

After running this command you should be able to run the mocha from any terminal window.

Reference external libraries using require

You need to use the require statement to import NodeJS’s built in assert module.

const assert = require('assert');

Setup Mocha

Mocha setup on the server side is very easy just be sure to have all your tests in the test folder and that all the modules they need is imported using require.

Run the tests

Run the unit tests by running the mocha command from the terminal in your projects root folder.