我一直在尝试模拟一个提供程序(在另一个提供程序中使用)并且无法设法将其嘲笑。 在测试中,我看到了实际的提供者功能,而不是模拟的功能。
这是(简化)代码:
首先,设置:(我删除了任何不需要的东西):
function ServiceToMock() {
this.functionMock = function () {
// do something...
};
this.$get = function () {
// doesn't matter
};
}
module('theModule').provider('serviceToMock', ServiceToMock);
function ServiceThatUsesMock(serviceToMock) {
serviceToMock.functionMock(); // I want the mocked function to run here but the actual one does
this.$get = function () {
// doesn't matter...
};
}
module('theModule').provider('serviceThatUsesMock', ServiceThatUsesMock);
如您所见,使用.provider()
定义了两个服务,第二个服务依赖于第一个服务。
单元测试:
let functionMock = jasmine.createSpy();
module('theModule');
module(function ($provide) {
$provide.provider('serviceToMock', function () {
this.functionMock = functionMock;
this.$get = () => ({});
this.test = 'aaa';
});
});
var serviceThatUsesMock;
beforeEach(inject(function (_serviceThatUsesMock_) {
serviceThatUsesMock = _serviceThatUsesMock_;
}));
it('should register for update failure', function () {
expect(functionMock).toHaveBeenCalled();
});
测试失败,因为真实函数被调用而不是被模拟的函数。
我做错了什么?
谢谢!