我有一个函数
var data = {};
var myFunc = function() {
data.stuff = new ClassName().doA().doB().doC();
};
我想测试一下 doA、doB 和 doC 都被调用了.
I'd like to test that doA, doB, and doC were all called.
我尝试像这样监视实例方法
I tried spying on the instance methods like this
beforeEach(function() {
spyOn(ClassName, 'doA');
};
it('should call doA', function() {
myFunc();
expect(ClassName.doA).toHaveBeenCalled();
});
但这只会给我一个doA() 方法不存在"的错误.
but that just gives me a "doA() method does not exist" error.
有什么想法吗?
你出错的地方在于你对如何在静态上下文中引用 JavaScript 方法的理解.您的代码实际上是在监视 ClassName.doA(即作为属性 doA 附加到 ClassName 构造函数的函数,它不是你想要的).
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).
如果您想检测何时在任何地方的任何 ClassName 实例上调用该方法,则需要监视原型.
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();
});
当然,这是假设 doA 存在于原型链中.如果它是一个自己的属性,那么如果不能引用 myFunc 中的匿名对象,就没有可以使用的技术.如果您可以访问 myFunc 中的 ClassName 实例,那将是理想的,因为您可以直接 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.
附:你真的应该把茉莉花"放在标题里.
P.S. You should really put "Jasmine" in the title.
这篇关于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 - 如何监视函数中的函数调用?)