假设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
答案 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() {
// ...
});
});