我想提供自己的功能来替换工厂,我也希望能够使用.and.callThrough()
来使用原始功能。我遇到的主要问题是我无法将工厂注入模拟模块语句。
describe("It", function() {
var mockFactory;
//This works, but the original functionality is gone at this point because I'm overriding it with $provide
beforeEach(angular.mock.module('myModule', function($provide) {
mockFactory = jasmine.createSpy('myFactory');
$provide.factory('myFactory', function() { return mockFactory });
}));
//This fails because I cant inject the actual factory into the module mock
beforeEach(angular.mock.module('myModule', function($provide, myFactory) {
mockFactory = jasmine.createSpy('myFactory', myFactory);
$provide.factory('myFactory', function() { return mockFactory });
}));
})
关于如何克服这个问题的任何想法?提前谢谢!
答案 0 :(得分:4)
您可以像这样使用$provide.decorator()
:
describe('It', function() {
var mockFactory;
beforeEach(module('myModule', function ($provide) {
$provide.decorator('myFactory', function ($delegate) {
mockFactory = jasmine.createSpy('myFactory', $delegate).and.callThrough();
return mockFactory;
});
}));
it('should call through', function () {
mockFactory('foo', 'bar');
expect(myFactory).toHaveBeenCalled();
});
});
希望这有帮助。