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

前端 未结 2 940
[愿得一人]
[愿得一人] 2021-02-01 06:43

Given the following code snippet, how would you create a Jasmine spyOn test to confirm that doSomething gets called when you run MyFunction

相关标签:
2条回答
  • 2021-02-01 07:48

    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();
    });
    
    0 讨论(0)
  • 2021-02-01 07:48

    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();
    
        });
    });
    
    0 讨论(0)
提交回复
热议问题