I've had a small issue that bothers me.. The following code shows an async test, in that test we test a code we have no control of (blackbox for the test, I can change it).
The blackbox code dispatches event when it's done, the test listens to this event and asserts the data.
the problem is when there is an assertion error, exception is thrown and cought by the promise error handler and not by the test framework, so the done function is never executes and we get timeout error for this test.
its easy to solve it by try & catch inside the it() block, but is it a good practice to ALWAYS have try & catch inside the it() block? so far I trusted the test framework to deal with exceptions
another problem, is that the error is silent, unless the catch prints it, and since its blackbox we cannot count on it.
the tips here helped me solve it, but I dont like the solutions: https://github.com/mochajs/mocha/issues/1128#issuecomment-40866763
it is different than other similar questions because in the it() block we dont have any reference to a promise object.
describe.only("test", function () {
var event;
// blackbox simulates a code we have no controler over
// inside this code we have a promise, when this promise resolves it triggers event
var blackbox = function () {
var promise = new Promise(function (resolve, reject) {
resolve();
});
promise.then(function () {
event(4);
}).catch(function (e) {
console.log(e);
});
};
it("async with blackbox promise", function (done) {
// this simulates event listenner, when the event is triggered the code executes
event = function (data) {
// this assertion works and everything is fine
data.should.be.equal(4);
// this assertion thrown exception that is being cought by the promise reject handler and
// isnt cought by the testing framework (chai / mocha)
data.should.be.equal(5);
// because the exception is thrown we never reach the done
done();
};
blackbox();
});
});