Skip to content

Instantly share code, notes, and snippets.

@jonepl
Created November 15, 2020 01:28
Show Gist options
  • Save jonepl/452a95c8a6fc6b86d02d64a14c17ea94 to your computer and use it in GitHub Desktop.
Save jonepl/452a95c8a6fc6b86d02d64a14c17ea94 to your computer and use it in GitHub Desktop.

Testing with Mocha and Chai

Mocha - a JavaScript test framework for Node.js programs, featuring browser support, asynchronous testing, test coverage reports, and use of any assertion library.

Chai - BDD (behavior driven development) / TDD (test driven development) assertion library for node and the browser that can be delightfully paired with any javascript testing framework.

Setup

  1. Makes sure you have a intialized NodeJS environment.

    $ npm init
    
  2. Install testing dependencies

    $ npm install mocha chai --save-dev
    
  3. Create a directory to house your test. Below is an example of testing an application

    root/
    ├─── app/
    │   └── app.js
    ├─── test/
    │   ├── appTest.js
    └── index.js
    

Example Test Snippet

// app.js
module.exports = function () {
    return 'hello';
}

// appTest.js
const assert = require('chai').assert;
const app = require('../app')

describe('App', function () {
    it('app should return hello', function () {
        assert.equal(app(), 'hello');
    });

    it('should return type string', function () {
        assert.typeOf(app(), 'string');
    })
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment