Mocha
This is an introduction to Mocha a JavaScript test framework.
Mocha is a JavaScript test framework that runs on Node.js and in the browser.
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.
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
v7.7.2
YUSUF-MacBook-Pro:mocha-project yusufshakeel$ npm -v
5.8.0
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.
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
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.
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
5.0.5
Or, use the following command.
$ node_modules/mocha/bin/mocha --version
5.0.5
Alright, in the next tutorial we will setup Mocha and our project to start writing test codes.
ADVERTISEMENT