Mocha - Introduction


Next →

This is an introduction to Mocha a JavaScript test framework.

What is Mocha?

Mocha is a JavaScript test framework that runs on Node.js and in the browser.

What are we going to do?

In this tutorial series we will be writing some JavaScript code and then testing our code using Mocha.

Now, before we start writing our code we have to setup our development environment. So, lets get started.

The complete project code of this tutorial series is there on my GitHub mocha-project repository.

But first, get Node.js and npm

To use Mocha we will need Node.js and npm.

So, head over to their website and download the latest stable version.

Here is a turoial on how to install Node.js and npm on Mac.

After installing Node.js and npm run the following command node -v and npm -v to check their versions.

At the time of writing this tutorial I was using the following versions.

YUSUF-MacBook-Pro:mocha-project yusufshakeel$ node -v
YUSUF-MacBook-Pro:mocha-project yusufshakeel$ npm -v
YUSUF-MacBook-Pro:mocha-project yusufshakeel$

To use Mocha v3 and up you will need npm v2 or newer and Node v4 or newer version.

Now create a new project

Open your favourite text editor or IDE and create a new project folder and name it mocha-project.

Feel free to use any name you like.

I will use the terminal to create the project folder and cd into it.

$ mkdir mocha-project && cd mocha-project

Initialise npm

Now run the following command npm init in the terminal or command prompt inside the mocha-project directory to initalise npm.

It will ask you to fill out some fields. You can ignore them for now as this is just an educational project. But for live project do fill the fields correctly and as per your project requirement.

On success it will create package.json file inside the project folder.

Time to install Mocha

We can install Mocha globally by running the following command.

$ npm install --global mocha

But for this tutorial series we will be installing Mocha as a development dependency. So, we will be running the following command.

$ npm install --save-dev mocha
npm notice created a lockfile as package-lock.json. You should commit this file.
+ mocha@5.0.5
added 24 packages from 283 contributors in 4.338s

Mocha will be installed in the node_modules directory.

We can check the version of mocha by running the following command.

$ npx mocha --version

Or, use the following command.

$ node_modules/mocha/bin/mocha --version

Alright, in the next tutorial we will setup Mocha and our project to start writing test codes.

Next →