Mocha - Setup Mocha for testing

Mocha

In this tutorial we will setup Mocha to start testing our JavaScript code.

In the previous tutorial we created a simple mocha-project and installed Mocha via npm.

Now, we will setup Mocha for testing our JavaScript code.

Set the test in the package.json file

Inside the package.json file we get the script property which is an object and it contains the test property.

By default it is set to the following.

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
}

So, to run Mocha via npm we have to set the test property to mocha || true.

So, change the following:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
}

To the following:

"scripts": {
  "test": "mocha || true"
}

Now if we run the following command npm run test npm will run Mocha which will run the tests for us.

$ npm run test

> mocha-project@1.0.0 test /Users/yusufshakeel/Documents/GitHub/mocha-project
> mocha || true

Warning: Could not find any test files matching pattern: test
No test files found

Note! Till now we have not written any test code so, we are getting No test files found message.

Mocha is looking for the test directory

In the above out we got the following warning line.

Warning: Could not find any test files matching pattern: test

As a convention we put our test code inside the test directory. And when we run the npm run test command Mocha looks for the test code inside that test directory.

So, lets go ahead and create the test directory inside our project directory.

$ mkdir test

Now, if we run mocha via npm we will not get the above warning. But we will also get no test result as we have not yet written any test.

$ npm run test

> mocha-project@1.0.0 test /Users/yusufshakeel/Documents/GitHub/mocha-project
> mocha || true

No test files found

Now we are ready to write some JavaScript code and then write tests.

See you in the next tutorial.