2013-01-04 27 views
2

我想驗證一個茉莉間諜是用this的某個對象調用的。我怎樣才能做到這一點?我如何用茉莉間諜來檢查'this'的值?

一個人爲的例子:

var spy = jasmine.createSpy('method'); 
var obj = {property: 'value'}; 
spy.apply(obj); 
// How can we verify that 'this' in the call to spy is 'obj'?​​​​​​​​ 

我創建了這個問題的fiddle

回答

2

雖然我找不到有關此功能的任何文檔(對不起,如果我錯過了某些內容),每次調用間諜時都會記錄this的值。

var spy = jasmine.createSpy('method'); 
var obj = { 
    property: 'value' 
}; 
spy.apply(obj); 
expect(spy.mostRecentCall.object).toEqual(obj); 

參見this fiddle進行演示。

+0

這是w是2.2中公共API的一部分。 http://jasmine.github.io/2.2/introduction.html#section-30 expect(foo.setBar.calls.first())。toEqual({object:foo,args:[123],returnValue:undefined }); – Jesse

0

對測試工作的時候,所以我決定寫定製間諜的匹配我遇到了這樣的問題:https://www.npmjs.com/package/jasmine-spy-matchers

使用他們,你可以訪問新的匹配:

expect(spy).toHaveBeenCalledWithContext(obj) 
 

 
//or 
 

 
expect(spy).toHaveBeenCalledWithContext(obj, 'foo', 'bar')

它工作方式類似於HaveBeenCalledWith但可以驗證context