javascript 如何在另一个方法中创建的对象上使用 Jasmine 间谍?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22291371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Jasmine spies on an object created inside another method?
提问by thinkbigthinksmall
Given the following code snippet, how would you create a JasminespyOn
test to confirm that doSomething
gets called when you run MyFunction
?
给定以下代码片段,您将如何创建JasminespyOn
测试以确认doSomething
在您运行时被调用MyFunction
?
function MyFunction() {
var foo = new MyCoolObject();
foo.doSomething();
};
Here's what my test looks like. Unfortunately, I get an error when the spyOn
call is evaluated:
这是我的测试的样子。不幸的是,在spyOn
评估调用时出现错误:
describe("MyFunction", function () {
it("calls doSomething", function () {
spyOn(MyCoolObject, "doSomething");
MyFunction();
expect(MyCoolObject.doSomething).toHaveBeenCalled();
});
});
Jasmine doesn't appear to recognize the doSomething
method at that point. Any suggestions?
JasminedoSomething
那时似乎不认识这种方法。有什么建议?
采纳答案by Gregg
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.
当您调用时,new MyCoolObject()
您会调用该MyCoolObject
函数并获得一个具有相关原型的新对象。这意味着当您spyOn(MyCoolObject, "doSomething")
不是在new
调用返回的对象上设置间谍时,而是在函数本身的可能doSomething
函数上设置间谍MyCoolObject
。
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();
});
回答by hyong
Alternatively, as Gregg hinted, we could work with 'prototype'. That is, instead of spying on MyCoolObject directly, we can spy on MyCoolObject.prototype.
或者,正如 Gregg 暗示的那样,我们可以使用“原型”。也就是说,我们可以监视 MyCoolObject.prototype,而不是直接监视 MyCoolObject。
describe("MyFunction", function () {
it("calls doSomething", function () {
spyOn(MyCoolObject.prototype, "doSomething");
MyFunction();
expect(MyCoolObject.prototype.doSomething).toHaveBeenCalled();
});
});