How to test chai with yield generator with exception

I'm trying to test a generator that should always throw an exception:

function* failureFunc() { yield* getThing('blabla'); //throws an error
}

How should I build the chai expect / should expression correctly? So far I couldn't get an expression to work I have tried:

chai.expect(yield* failureFunc()).to.throw(Error);
chai.expect(yield* failureFunc()).to.be.rejectedWith(Error);

tried also adding some chai-generator functions. Nothing seems to work. Not sure what is the correct way to build this expression.

1 Answer

You have to iterate over the generator. Here are ways you can do it:

const chai = require("chai");
const cap = require("chai-as-promised");
const Promise = require("bluebird");
chai.use(cap);
function* failureFunc() { yield* getThing('blabla'); // Throws an error, because getThing is not defined.
}
chai.expect(() => Array.from(failureFunc())).to.throw(Error);
chai.expect(Promise.coroutine(failureFunc)()).to.be.rejectedWith(Error);

In the first case, I use Array.from which will try to iterate over the whole generator. By doing this, you can catch an error at the any iteration. (It is in theory possible for an generator to throw at any iteration cycle.) You can use any method that iterates over the whole generator. Or if you are testing a case that will fail on the 1st iteration you could test on () => failureFunc().next().

In the 2nd case, I use Bluebird's Promise.coroutine to transform the generator into a function that returns a promise and check that the promise is rejected. Since the promise resolves only after the generator has finished iterating, this ensures that it goes over all iterations.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like