鉴于以下代码片段,您将如何创建 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模板网!
在 javascript 认为文档“准备好"之前,如何让How can I get my jasmine tests fixtures to load before the javascript considers the document to be quot;readyquot;?(在 javascript 认为文档“准备好
jasmine 运行和等待实际上是做什么的?What do jasmine runs and waitsFor actually do?(jasmine 运行和等待实际上是做什么的?)
如何提供模拟文件来更改 <input type='filHow to provide mock files to change event of lt;input type=#39;file#39;gt; for unit testing(如何提供模拟文件来更改 lt;input type=filegt; 的事
如何使用 Jasmine 对链式方法进行单元测试How to unit test a chained method using Jasmine(如何使用 Jasmine 对链式方法进行单元测试)
如何将 $rootScope 注入 AngularJS 单元测试?How do I inject $rootScope into an AngularJS unit test?(如何将 $rootScope 注入 AngularJS 单元测试?)
Jasmine - 如何监视函数中的函数调用?Jasmine - How to spy on a function call within a function?(Jasmine - 如何监视函数中的函数调用?)