2015-03-31 158 views
19

我想測試一個函數返回一個承諾。按照承諾測試拒絕與拒絕

在此特定試驗中,承諾預計與含有經典message字段Error對象被拒絕(在該測試中,它預計相當於"my error message")和一個自定義字段我添加命名code,它是一個字符串(比如「EACCESS」,「ERIGHT」等,在這個測試中預計等於"EFOO"

我想使用chai-as-promised。

return expect(foo()).to.eventually.be.rejectedWith("my error message"); 

這種說法是工作,但現在我想測試code場了。
如何做到這一點?

+1

重複爲[測試用於被拒絕的承諾的特定屬性(http://stackoverflow.com/questions/23985949/testing-for-specific-properties-of-rejected-promises-with-mocha-and- chai-as-pro) – 2015-03-31 08:43:53

回答

24

如果你使用Chai-As-Promised(因爲你說你是),那麼它允許鏈接關閉的rejectedWith - 它套,環斷言對象是錯誤對象 - rejectedWith()後意味着什麼現在要斷言上錯誤。這讓你做很酷的事情,如:

return expect(foo()).to.eventually 
    .be.rejectedWith("my error message") 
    .and.be.an.instanceOf(Error) 
    .and.have.property('code', 'EFOO'); 

一些柴方法也鏈條,所以你可以用它來做出有關該錯誤的一些相當深嵌套斷言:

return expect(foo()).to.eventually 
    .be.rejectedWith("my error message") 
    .and.have.property('stack') 
    .that.includes('myfile.js:30') 
+2

因爲某些原因,這對我不起作用。不管我做錯誤消息字符串它總是通過。 – chovy 2016-04-15 20:37:52

+0

@chovy可以粘貼foo()的方法代碼。如果您正在使用return語句,並且在拒絕處理程序中,您可以驗證您的系統正在測試(方法),如果您明確拒絕...否則promise將被視爲已解決。 – 2016-05-05 03:55:04

+0

'foo()'返回'$ q.defer()。promise' - 顯然chai-as-promised與angular的'$ q'有關係。 – chovy 2016-05-05 22:45:37

28

有5.1版。 ChaiAsPromised,從Keithamus解決方案並沒有爲我工作的0 - rejectedWith並沒有給我的錯誤對象斷言,但「拒絕」做的:

return expect(foo()) 
    .to.be.rejected 
    .and.be.an.instanceOf(Error) 
    .and.have.property('code', 'EFOO'); 

對於斷言多個屬性

return expect(foo()) 
    .to.be.rejected 
    .then(function(error) { 
     expect(error).to.have.property('name', 'my error message'); 
     expect(error).to.have.property('code', 'EFOO'); 
    });