如何使用 Jasmine 处理异步代码中抛出的错误?

How to deal with thrown errors in async code with Jasmine?

以下测试会导致 Jasmine(2.3.4,运行 在浏览器中通过 Karma)崩溃,而不是 运行 任何后续测试

it('should report as failure and continue testing', function (done) {
  setTimeout(function () {
    throw new SyntaxError('some error');
    done();
  }, 1000);
});

我怎样才能让这个测试正确地报告自己失败并继续进行后续测试?

模拟时钟会给你预期的结果。 通常模拟时钟是测试超时的最佳实践。

describe('foo', function () {
    beforeEach(function () {
        timerCallback = jasmine.createSpy("timerCallback");
        jasmine.clock().install();
    });
    afterEach(function () {
        jasmine.clock().uninstall();
    });
    it('should report as failure and continue testing', function (done) {
        setTimeout(function () {
            throw new SyntaxError('some error');
            done();
        }, 1000);
        jasmine.clock().tick(1001);
    });
});