Unit Testing Koa

Koa uses generator functions for asynchronous operations. Traditional test runners like mocha or jest do not support generators. Here we will use co-mocha to wrap mocha to add support for generators.

Install the packages. We will need mocha, co-mocha and chai.

npm install mocha co-mocha chai --save-dev

In your package.json setup mocha as the test runner.

  "scripts": {
    "start": "node app.js",

Create a test folder in your project root. Within that folder create a test script called my_test.js. Add these lines to the file.

let coMocha = require("co-mocha")
let assert = require("chai").assert

function *myGenerator() {
    return Promise.resolve(20)

it('Tests generators', function * () {
  let value = yield myGenerator()

  assert.equal(value, 20, "Value must be 20")

When you bring in the co-mocha module it automatically wraps over the mocha API and adds support for generators. This lets us supply a generator function to the it() method.

You can now run tests the usual way.

npm test

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s