如何在另一个方法内部创建的对象上使用Jasmine间谍? [英] How to use Jasmine spies on an object created inside another method?
问题描述
给出以下代码段,您将如何创建 Jasmine spyOn
测试确定在运行MyFunction
时是否调用了doSomething
?
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间谍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!