Question

I want to provide my own function to replace a factory, and I also want the ability to use .and.callThrough() to use the original functionality. The main problem I'm running into is that I can't inject a factory in to the mock module statement.

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 });
    }));

})

Any ideas on how to overcome this? Thanks in advance!

Was it helpful?

Solution

You could use the $provide.decorator() like this:

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();
   });
});

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top