Karma, Mocha, Chai, Sinon? - Quick Overview

Since we're sorta on a roll to 'up our [tech-stack] game' at iHerb, we've been also throwing around the idea of implementing client-side unit tests.

Since I've never worked with unit-testing before, I figured it'd be nice to jump in and get myself up to speed.

I'd heard a lot of names thrown around, and this is just a brain dump to try make sense of a popular testing stack: Karma, Mocha, Chai, Sinon.

Karma

Karma is a testing environment / CLI runner that lets you run your tests on multiple browsers/platforms.

Karma can be configured to run in the background as you make changes to your files and can launch multiple browsers, concurrently.

Karma will auto-load all sibling node modules starting with karma-. This means if Karma is installed in the node_modules directory, all other modules starting with karma- will be auto-loaded for us (karma-mocha, karma-chai, etc). So, Mocha will be fetched as the karma-mocha node module and we won't need to manually load it ourselves.

Below is a sample of the karma.conf.js

files: [  
    "node_modules/chai/chai.js",
    "src/**/*.js",
    "tests/**/*.js"
]
Mocha

Mocha is a testing framework that is recommended for use with Redux, and it is responsible for running our tests and reporting back which failed.

Mocha does not have a built in assertion library, Chai will be used.

Chai

Chai provides various assertion interfaces that make your tests more readable and intuitive.

There are 3 styles for assertions with Chai:
The assert style, expect style, and the should style.

They essentially accomplish the same thing, but expect is the recommended assertion style since it provides a nicer human-readable format.

expect(foo).to.be.a('string');

The should style also provides a human-readable format, but it apparently extends the Object.prototype which seems messy and can possibly cause issues in the future.

Sinon

Sinon is a test-double library that allows mocking and stubbing different components, as well as faking server connections.

The idea with unit testing, is that we only want to test isolated functions. We shouldn't actually make live calls to any APIs or server since: 1) it's slower, and 2) it the role of functional/integration tests.

Unit tests should be only be concerned with checking function logic.

Sinon breaks up test doubles into three different categories: spies, stubs, and mocks

Test doubles can be thought of as stunt doubles: they replace one object with another for testing purposes.

Duncan Leung

Front End Developer at iHerb.com

Irvine, CA

Subscribe to Duncan Leung: Javascript and Front End Development

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!