問題描述
我正在嘗試為 Jasmine 測試框架 編寫一個測試,它預計會出錯.目前我正在使用來自 GitHub 的 Jasmine Node.js 集成.
I'm trying to write a test for the Jasmine Test Framework which expects an error. At the moment I'm using a Jasmine Node.js integration from GitHub.
在我的 Node.js 模塊中,我有以下代碼:
In my Node.js module I have the following code:
throw new Error("Parsing is not possible");
現在我嘗試編寫一個預期此錯誤的測試:
Now I try to write a test which expects this error:
describe('my suite...', function() {
[..]
it('should not parse foo', function() {
[..]
expect(parser.parse(raw)).toThrow(new Error("Parsing is not possible"));
});
});
我也嘗試了 Error()
和其他一些變體,但不知道如何使它工作.
I tried also Error()
and some other variants and just can't figure out how to make it work.
推薦答案
嘗試使用匿名函數:
expect( function(){ parser.parse(raw); } ).toThrow(new Error("Parsing is not possible"));
您應該將一個函數傳遞給 expect(...)
調用.您的錯誤代碼:
you should be passing a function into the expect(...)
call. Your incorrect code:
// incorrect:
expect(parser.parse(raw)).toThrow(new Error("Parsing is not possible"));
正在嘗試實際調用 parser.parse(raw)
以嘗試將結果傳遞給expect(...)
,
is trying to actually call parser.parse(raw)
in an attempt to pass the result into expect(...)
,
這篇關于如何編寫一個期望在 Jasmine 中拋出“錯誤"的測試?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!