Mocha测试套件因未捕获的异常而暂停

Mocha test suite halted on uncaught exception

本文关键字:异常 暂停 测试 套件 Mocha      更新时间:2023-09-26

我无法阻止未捕获异步异常停止一组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)

它正在停止,因为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();
    });
});