Introduction to Testing with Mocha and Chai
Tags: testing, mocha, chai, javascript
Published: 2020-03-14 06:07:14

In this quick tutorial we will learn what Mocha and Chai are and how to make use of them to test our JavaScript code.
And in case you are fascinated with [Cypress] (https://dev.to/bushraalam/cypress-end-to-end-testing-framework-3naa) (like we are!) then that's another good reason to explore them as Mocha and Chai are hand picked and integrated in Cypress.

----

<p>
> If you prefer to watch and learn, hop on to our [JS for Testers series on Youtube] (https://bit.ly/2zoanJh)
Subscribe to my Youtube Channel - [QA Camp](https://www.youtube.com/channel/UC6dkzt_Q4i5h8NUJmZideFQ/playlists)!
<p>

{% youtube zHzaUtHncQg %}


-----


#Mocha

* Mocha is a JavaScript test framework.
* Mocha can be used for both browser-based testing and Node.js testing


###Installation

**Prerequisite (for both Mocha and Chai):**
We need to install Node.js because we need npm (to install mocha and chai) which gets downloaded along with node.js.
You can download node.js from here: [https://nodejs.org/en/download/](https://nodejs.org/en/download/)
Once download is complete, launch and run through the installer.
To verify successful installation check the version:

```
node -v
npm -v
```


**Install Mocha**

Once npm is installed, you can Install Mocha either globally or as a development dependency for your project:

```
npm install --global mocha

npm install --save-dev mocha
```

###Mocha Basic Spec

```js
describe('Basic Mocha String Test', function () {
 it('should return number of charachters in a string', function () {
        ....
    });
 it('should return first charachter of the string', function () {
       ....
    });
});
```

*A test file is called a <b>'Spec'</b>. Spec is short for 'Specification'. Specification in terms of a test refers to the technical details of a given feature or application which must be fulfilled.*

<code>describe()</code> and <code>it()</code> form the backbone of Mocha. 
* <code>describe()</code> - collection of individual tests 
It takes two parameters, first one is the meaningful name to functionality under test and second one is the function which contains one or multiple tests. describe() can be nested.
* <code>it()</code>  -  an **I**ndividual **T**est
It takes two parameters, first parameter is name to the test and second parameter is function which holds the body of the test.

You can skip an individual test (<code>it()</code>) or a collection of tests (<code>describe()</code>) and can also specify to run a single test or a collection of tests using <code>.skip</code> and <code>.only</code>

```js
describe('Array', function() {
  describe('#indexOf()', function() {
    it.skip('should return -1 unless present', function() {
      // this test will not be run
    });

    it('should return the index when present', function() {
      // this test will be run
    });
  });
});
```

```js
describe('Array', function() {
  describe('#indexOf()', function() {
    it.only('should return -1 unless present', function() {
      // this test will be run
    });

    it('should return the index when present', function() {
      // this test will not be run
    });
  });
});
```

###Hooks
With its default "BDD"-style interface, Mocha provides the hooks <code>before()</code>, <code>after()</code>, <code>beforeEach()</code>, and <code>afterEach()</code>. These should be used to set up preconditions and clean up after your tests.

```js
describe('hooks', function() {
  before(function() {
    // runs before all tests in this block
  });

  after(function() {
    // runs after all tests in this block
  });

  beforeEach(function() {
    // runs before each test in this block
  });

  afterEach(function() {
    // runs after each test in this block
  });

  // test cases
});
```


### To Execute

Set up a test script in package.json:

```json
"scripts": {
  "test": "mocha"
}
```

Then run tests with:

```
npm test
```

###Assertions

Assertions are critical to writing test as they validate whether or not the test passed successfully.
Mocha allows you to use any assertion library you wish such as should.js, expect.js, chai, better-assert and unexpected.


-----


#Chai

* Chai is a BDD / TDD assertion library for node and the browser
* Chai can be paired with any javascript testing framework (for instance Mocha)
* Chai has several interfaces that allow the developer to choose. The chain-capable BDD styles provide an expressive language & readable style, while the TDD assert style provides a more classical feel.
BDD (more popular) - expect, should 
TDD - assert


###Installation

```
npm install --save-dev chai
```


###Assertion Styles

Chai provides the following assertion styles:

####1. Assert style
```js
var assert = require('chai').assert;
var foo = “bar”;

assert.typeOf(foo, 'string');
assert.equal(foo, 'bar');
```

####2. Expect style
```js
var expect = require('chai').expect;
var foo = “bar”;

expect(foo).to.be.a('string');
expect(foo).to.equal('bar');
```

####3. Should style
```js
var should = require('chai').should();
var foo = “bar”;

foo.should.be.a('string');
foo.should.equal('bar');
```


----

<p>
> If you prefer to watch and learn, hop on to our [Cypress series on Youtube] (https://bit.ly/2n48zPJ)
Subscribe to my Youtube Channel - [QA Camp](https://www.youtube.com/channel/UC6dkzt_Q4i5h8NUJmZideFQ/playlists)!
<p>

{% youtube IMx7Ng-T2mw %}


-----