How to make assertions inside a promise when any errors thrown don't bubble up?

三世轮回 提交于 2020-01-03 08:42:40

问题


Running this with mocha results in timing out, rather than letting mocha catch the error so it could fail immediately..

var when = require('when');
var should = require('should');

describe('', function() {
    it('', function(done) {
        var d = when.defer();
        d.resolve();
        d.promise.then(function() {
            true.should.be.false;
            false.should.be.true;
            throw new Error('Promise');
            done();
}); }); });

http://runnable.com/me/U7VmuQurokZCvomD

Is there another way to make assertions inside the promise, such that when they fail they are caught by mocha causing it to fail immediately?


As per chai recommendation, I looked into it and it seems I have to have a direct access to the promise object, right? The problem is that I'm not using promise directly.. My bad if I simplified but This would be a more closer to reality example

function core_library_function(callback){
    do_something_async(function which_returns_a(promise){
        promise.then(function(){
            callback(thing);
}); }); }

describe('', function() {
    it('', function(done) {
        core_library_function(function(thing){
            ...
            done();                         
}); }); });

So I really have no control over the promise directly, it's abstracted far far away.


回答1:


When using promises with Mocha, you'll have to return the promise in the test and will want to remove the done parameter since the callback isn't being used.

it('', function() {
    var d = when.defer();
    d.resolve();
    return d.promise.then(function() {
        throw new Error('Promise');
    });
});

This is described in the docs under Working with Promises:

Alternately, instead of using the done() callback, you can return a promise.



来源:https://stackoverflow.com/questions/24557583/how-to-make-assertions-inside-a-promise-when-any-errors-thrown-dont-bubble-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!