模拟/监视构造函数“x.Thing()”

时间:2017-01-09 20:24:26

标签: javascript mocking jasmine spy

假设x是外部库,Thing是可以从x构建的对象。这些都包含在Angular服务中,如下所示:

app.service('thingService', function() {
    var thing;

    this.createThing = function(thingParam){
        thing = new x.Thing(thingParam);
    }
}); 

我最初的尝试包括:

xSpy = jasmine.createSpyObj('x', ['Thing']);
spyOn(window, 'x').andReturn('xSpy');

但它仍然抱怨x() method does not exist应该构建Thing

1 个答案:

答案 0 :(得分:-1)

您的尝试

xSpy = jasmine.createSpyObj('x', ['Thing']);
spyOn(window, 'x').andReturn('xSpy');

错了:

spyOn()用间谍替换方法,因为x是一个不起作用的对象。这就是您获得异常x() method does not exist

的原因

假设您的示例,您只需替换属性:

describe("Test", function() {
    var origThing;

    beforeEach(function() {
        // create spy object for Thing that provides its methods
        var mockedThingInterface = jasmine.createSpyObj('Thing', ['methodA', 'methodB']);

        mockedThingInterface.methodA.and.returnValue(1);
        mockedThingInterface.methodB.and.returnValue(2);

        // remember original constructor
        origThing = x.Thing;

        // replace the constructor
        x.Thing = function() {
            return mockedThingInterface;
        }
    });

    afterEach(function() {
        // restore when finished
        x.Thing = origThing;
    });

    it("should ...", function() {
        // ...
    });
});