Creating Tests with Mocha

Course Home | Code Example(s)

So as mentioned in the first Mocha lesson, Mocha provides us with the framework to create tests in Mocha and a mechanism for running tests. Now aside from assertions, the tests themselves contain little else from Mocha. The majority of the code will be calls to other classes and libraries to help us interact with our application/codebase.

So let’s assume we’ve written some code that we want to turn into a test. We want to create our first test.

First up we need to create a folder named test in our project. As default, Mocha looks for a test folder and then executes any test files that exist in that folder:

mkdir test

Once you have your test folder, create a file and drop the following code in that has comments to explain each section:

// We need someway to assert if a value is true to return a pass/fail
// result. We'll look into assertions in more detail later, but for now
// we will use Nodes' standard assert library.
var assert = require('assert');

// We start by using the describe function in which our tests are created.
// As you will see when you run this test, the string we provide is added
// into the report to make it more readable and give your tests context.
describe('Maths calculation', function() {

  // The 'it' function is next to call, where we can name our test and then
  // execute the code we want to run for our test.
  it('should return the correct value when two numbers are added', function() {
    // Here is the code for our test that is triggered by Mocha
    var result = 1 + 1;

    assert.equal(result, 2);
  });

});

Finally, once your code is created and saved head to your terminal/command line and head to your projects root folder (meaning don’t run this inside your test folder as it will fail) and run mocha

> mocha


 Maths calculation
   ✓ should return the correct value when two numbers are added


 1 passing (6ms)

As you can see we’ve created a single test in Mocha which is then run and the result is shown in your terminal to give you feedback. We will look at more advanced options around reporting when running Mocha later. For now we can see that our test is passing.

Next Lesson ➔

Resources

Mocha - Getting started

Mark Winteringham's photo
Author

Mark Winteringham

@2bittester

Mark Winteringham is a tester, toolsmith and the Ministry of Testing DojoBoss with over 10 years experience providing testing expertise on award-winning projects across a wide range of technology sectors including BBC, Barclays, UK Government and Thomson Reuters. He is an advocate for modern risk-based testing practices and trains teams in Automation in Testing, Behaviour Driven Development and Exploratory testing techniques. He is also the co-founder of Software Testing Clinic a community raising awareness of careers in testing and improving testing education. You can find him on Twitter @2bittester.

Comments