Scholle Scholle - 1 year ago 206
Node.js Question

How to use Mocha with Promises/ES6 generators?

I want to use

ES6 generators
and optionally with
. After some research, I build the following code snippet:

describe('test', function() {
it('should not work', function() {
expect(function() {
return co(function*() {
yield Service.validate();
}).to.throw(new Error('error'));

Service.validate throws
new Error('error')
, and thats what I

module.exports = {
validate: function() {
return co(function*() {
// use yield to access db and so on
throw new Error('error');

However, the following code throws
AssertionError: expected [Function] to throw 'Error: error'
. Can anyone help?

Answer Source

co returns a promise, and errors thrown inside it will be turned into rejected Promises. So you have to test for a rejected Promise rather than an exception. This code works:

var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
var co = require("co");

var expect = chai.expect;
chai.use(chaiAsPromised); // Register chai-as-promised with Chai.

describe('test', function() {
 it('should not work', function() {
     return expect(co(function*() {
         throw new Error("testing failure!");
    })), "testing failure!");

Note how this does return expect(...). When you test promises with expect, it returns a promise, which can be returned to Mocha so that it can know when the test is over.