問題描述
鑒于以下代碼片段,您將如何創建 Jasmine spyOn
測試以確認 doSomething
在您運行 MyFunction
時被調用?
Given the following code snippet, how would you create a Jasmine spyOn
test to confirm that doSomething
gets called when you run MyFunction
?
function MyFunction() {
var foo = new MyCoolObject();
foo.doSomething();
};
這是我的測試的樣子.不幸的是,在評估 spyOn
調用時出現錯誤:
Here's what my test looks like. Unfortunately, I get an error when the spyOn
call is evaluated:
describe("MyFunction", function () {
it("calls doSomething", function () {
spyOn(MyCoolObject, "doSomething");
MyFunction();
expect(MyCoolObject.doSomething).toHaveBeenCalled();
});
});
Jasmine 此時似乎無法識別 doSomething
方法.有什么建議嗎?
Jasmine doesn't appear to recognize the doSomething
method at that point. Any suggestions?
推薦答案
當您調用 new MyCoolObject()
時,您會調用 MyCoolObject
函數并使用相關原型.這意味著當您 spyOn(MyCoolObject, "doSomething")
時,您不是在 new
調用返回的對象上設置間諜,而是在可能的 MyCoolObject
函數本身的>doSomething 函數.
When you call new MyCoolObject()
you invoke the MyCoolObject
function and get a new object with the related prototype. This means that when you spyOn(MyCoolObject, "doSomething")
you're not setting up a spy on the object returned by the new
call, but on a possible doSomething
function on the MyCoolObject
function itself.
您應該能夠執行以下操作:
You should be able to do something like:
it("calls doSomething", function() {
var originalConstructor = MyCoolObject,
spiedObj;
spyOn(window, 'MyCoolObject').and.callFake(function() {
spiedObj = new originalConstructor();
spyOn(spiedObj, 'doSomething');
return spiedObj;
});
MyFunction();
expect(spiedObj.doSomething).toHaveBeenCalled();
});
這篇關于如何在另一個方法中創建的對象上使用 Jasmine 間諜?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!