問題描述
如果我在測試中包含永遠(yuǎn)不會(huì)到達(dá)的代碼(例如,promise 序列的 fail
子句),我該如何強(qiáng)制測試失敗?
If I have code in a test that should never be reached (for example the fail
clause of a promise sequence), how can I force-fail the test?
我使用類似 expect(true).toBe(false);
之類的東西,但這并不漂亮.
I use something like expect(true).toBe(false);
but this is not pretty.
另一種方法是等待測試超時(shí),我想避免這種情況(因?yàn)樗苈?.
The alternative is waiting for the test to timeout, which I want to avoid (because it is slow).
推薦答案
Jasmine 提供了一個(gè)全局方法 fail()
,可以在 spec 塊中使用 it()
并且還允許使用自定義錯(cuò)誤消息:
Jasmine provides a global method fail()
, which can be used inside spec blocks it()
and also allows to use custom error message:
it('should finish successfully', function (done) {
MyService.getNumber()
.success(function (number) {
expect(number).toBe(2);
done();
})
.fail(function (err) {
fail('Unwanted code branch');
});
});
這是 Jasmine 的內(nèi)置功能,與我在下面提到的錯(cuò)誤"方法相比,它在任何地方都能正常工作.
This is built-in Jasmine functionality and it works fine everywhere in comparison with the 'error' method I've mentioned below.
更新前:
您可以從該代碼分支拋出錯(cuò)誤,它會(huì)立即使規(guī)范失敗,您將能夠提供自定義錯(cuò)誤消息:
You can throw an error from that code branch, it will fail a spec immediately and you'll be able to provide custom error message:
it('should finish successfully', function (done) {
MyService.getNumber()
.success(function (number) {
expect(number).toBe(2);
done();
})
.fail(function (err) {
throw new Error('Unwanted code branch');
});
});
但是你應(yīng)該小心,如果你想從 Promise 成功處理程序 then()
拋出一個(gè)錯(cuò)誤,因?yàn)殄e(cuò)誤會(huì)被吞沒在那里并且永遠(yuǎn)不會(huì)出現(xiàn).此外,您應(yīng)該注意應(yīng)用程序中可能存在的錯(cuò)誤處理程序,它們可能會(huì)在您的應(yīng)用程序中捕獲此錯(cuò)誤,因此它不會(huì)導(dǎo)致測試失敗.
But you should be careful, if you want to throw an error from Promise success handler then()
, because the error will be swallowed in there and will never come up. Also you should be aware of the possible error handlers in your app, which might catch this error inside your app, so as a result it won't be able to fail a test.
這篇關(guān)于強(qiáng)制失敗 Jasmine 測試的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!