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

旧巷老猫 提交于 2019-12-03 05:51:39

问题


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

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 doesn't appear to recognize the doSomething method at that point. Any suggestions?


回答1:


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



回答2:


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

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

    });
});


来源:https://stackoverflow.com/questions/22291371/how-to-use-jasmine-spies-on-an-object-created-inside-another-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!