javascript 如何在另一个方法中创建的对象上使用 Jasmine 间谍?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22291371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:51:56  来源:igfitidea点击:

How to use Jasmine spies on an object created inside another method?

javascripttestingjasminespy

提问by thinkbigthinksmall

Given the following code snippet, how would you create a JasminespyOntest to confirm that doSomethinggets called when you run MyFunction?

给定以下代码片段,您将如何创建JasminespyOn测试以确认doSomething在您运行时被调用MyFunction

function MyFunction() {
    var foo = new MyCoolObject();
    foo.doSomething();
};

Here's what my test looks like. Unfortunately, I get an error when the spyOncall is evaluated:

这是我的测试的样子。不幸的是,在spyOn评估调用时出现错误:

describe("MyFunction", function () {
    it("calls doSomething", function () {

        spyOn(MyCoolObject, "doSomething");
        MyFunction();
        expect(MyCoolObject.doSomething).toHaveBeenCalled();

    });
});

Jasmine doesn't appear to recognize the doSomethingmethod at that point. Any suggestions?

JasminedoSomething那时似乎不认识这种方法。有什么建议?

采纳答案by Gregg

When you call new MyCoolObject()you invoke the MyCoolObjectfunction 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 newcall, but on a possible doSomethingfunction on the MyCoolObjectfunction itself.

当您调用时,new MyCoolObject()您会调用该MyCoolObject函数并获得一个具有相关原型的新对象。这意味着当您spyOn(MyCoolObject, "doSomething")不是在new调用返回的对象上设置间谍时,而是在函数本身的可能doSomething函数上设置间谍MyCoolObject

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();
});

回答by hyong

Alternatively, as Gregg hinted, we could work with 'prototype'. That is, instead of spying on MyCoolObject directly, we can spy on MyCoolObject.prototype.

或者,正如 Gregg 暗示的那样,我们可以使用“原型”。也就是说,我们可以监视 MyCoolObject.prototype,而不是直接监视 MyCoolObject。

describe("MyFunction", function () {
    it("calls doSomething", function () {
        spyOn(MyCoolObject.prototype, "doSomething");
        MyFunction();
        expect(MyCoolObject.prototype.doSomething).toHaveBeenCalled();

    });
});