Jasmine - 如何监视实例方法

2022-01-11 00:00:00 jasmine javascript

我有一个函数

var data = {};
var myFunc = function() {
  data.stuff = new ClassName().doA().doB().doC();
};

我想测试一下 doAdoBdoC 都被调用了.

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.

相关文章