如何使用Jasmine处理异步代码中抛出的错误?
问题描述:
以下测试导致Jasmine(2.3.4,通过Karma在浏览器中运行)崩溃并且不运行任何后续测试
The following test causes Jasmine (2.3.4, run in browser via Karma) to crash and not run any subsequent tests
it('should report as failure and continue testing', function (done) {
setTimeout(function () {
throw new SyntaxError('some error');
done();
}, 1000);
});
我如何正确地将此测试报告为失败并继续进行后续测试?
How can I have this test correctly report itself as a failure and carry on with subsequent tests?
答
模拟时钟会给你预期的结果。
模拟时钟通常是测试超时的最佳做法。
Mocking the clock will give you the expected result. Mocking the clock in general is a best practice for testing timeouts.
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);
});
});