摩卡测试套件因未捕获的异常而停止

时间:2015-03-04 04:12:31

标签: javascript node.js testing mocha

我无法阻止 Uncaught Async Exception 停止一系列mocha测试。看起来它应该只是测试失败,但mocha进程退出。对于给定的测试用例:

describe('AsyncWow', () => {

    it('should proceeed after this test', (done) => {
        setTimeout(() => {
            throw new Error('boom');
            done();
        });
    });

    it('but never gets here', (done) => {
        done();
    });

});

产生终端输出:

  AsyncWow

/source/test/foo.test.js:6
         throw new Error('boom');
               ^
Error: boom
    at [object Object]._onTimeout (/source/test/foo.test.js:6:16)
    at Timer.listOnTimeout (timers.js:110:15)

1 个答案:

答案 0 :(得分:0)

它正在暂停,因为永远不会调用done()(因为错误之后,它会搜索异常处理程序,并且永远不会触及下一行),

我会将代码更改为...

describe('AsyncWow', () => {
    it('should proceeed after this test', (done) => {
        setTimeout(() => {
            try{
                throw new Error('boom');
                done(new Error('This line should not be reached.'));
            }catch(e){
                done(); 
            }

        });
    });
    it('but never gets here', (done) => {
        done();
    });
});

或者如果您希望错误导致测试失败......

describe('AsyncWow', () => {
    it('should proceeed after this test', (done) => {
        setTimeout(() => {
            try{
                throw new Error('boom');
                done();
            }catch(e){
                done(e); 
            }

        });
    });
    it('but never gets here', (done) => {
        done();
    });
});