問題描述
我有一個(gè)函數(shù)
var data = {};
var myFunc = function() {
data.stuff = new ClassName().doA().doB().doC();
};
我想測試一下 doA
、doB
和 doC
都被調(diào)用了.
I'd like to test that doA
, doB
, and doC
were all called.
我嘗試像這樣監(jiān)視實(shí)例方法
I tried spying on the instance methods like this
beforeEach(function() {
spyOn(ClassName, 'doA');
};
it('should call doA', function() {
myFunc();
expect(ClassName.doA).toHaveBeenCalled();
});
但這只會給我一個(gè)doA() 方法不存在"的錯(cuò)誤.
but that just gives me a "doA() method does not exist" error.
有什么想法嗎?
推薦答案
你出錯(cuò)的地方在于你對如何在靜態(tài)上下文中引用 JavaScript 方法的理解.您的代碼實(shí)際上是在監(jiān)視 ClassName.doA
(即作為屬性 doA
附加到 ClassName
構(gòu)造函數(shù)的函數(shù),它不是你想要的).
Where you went wrong was your understanding of how to refer to methods in JavaScript in a static context. What your code is actually doing is spying on ClassName.doA
(that is, the function attached to the ClassName
constructor as the property doA
, which is not what you want).
如果您想檢測何時(shí)在任何地方的任何 ClassName
實(shí)例上調(diào)用該方法,則需要監(jiān)視原型.
If you want to detect when that method gets called on any instance of ClassName
anywhere, you need to spy on the prototype.
beforeEach(function() {
spyOn(ClassName.prototype, 'doA');
});
it('should call doA', function() {
myFunc();
expect(ClassName.prototype.doA).toHaveBeenCalled();
});
當(dāng)然,這是假設(shè) doA
存在于原型鏈中.如果它是一個(gè)自己的屬性,那么如果不能引用 myFunc
中的匿名對象,就沒有可以使用的技術(shù).如果您可以訪問 myFunc
中的 ClassName
實(shí)例,那將是理想的,因?yàn)槟梢灾苯?spyOn
該對象.
Of course, this is assuming that doA
lives in the prototype chain. If it's an own-property, then there is no technique that you can use without being able to refer to the anonymous object in myFunc
. If you had access to the ClassName
instance inside myFunc
, that would be ideal, since you could just spyOn
that object directly.
附:你真的應(yīng)該把茉莉花"放在標(biāo)題里.
P.S. You should really put "Jasmine" in the title.
這篇關(guān)于Jasmine - 如何監(jiān)視實(shí)例方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!