如何在另一个方法内部创建的对象上使用Jasmine间谍? [英] How to use Jasmine spies on an object created inside another method?

查看:73
本文介绍了如何在另一个方法内部创建的对象上使用Jasmine间谍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码段,您将如何创建 Jasmine spyOn测试确定在运行MyFunction时是否调用了doSomething?

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间谍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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