Jasmine - 如何spyOn实例方法 [英] Jasmine - how to spyOn instance methods

查看:125
本文介绍了Jasmine - 如何spyOn实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能

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 (即附加到<$ c的函数) $ c> ClassName 构造函数作为属性 doA ,这不是你想要的。)

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.

PS你应该把Jasmine放在标题中。

P.S. You should really put "Jasmine" in the title.

这篇关于Jasmine - 如何spyOn实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆