vendredi 26 juin 2015

Mocking custom provider injected into provider when unit testing Angular in Jasmine

I'm unit testing a provider in Jasmine, which relies on another provider. There's no configuration associated with this provider. When mocking a provider, I've read you're supposed to use something like

beforeEach(function ($provide) {
    mockInjectedProvider = { };
    $provide.value('injected', mockInjectedProvider );
});

which works fine for me when injecting a custom provider into a service. When injecting them into a provider it doesn't work though. The code doesn't fail, but what gets executed when testing is the actual provider, not the mocked one. Abstracted example below.

var mockInjectedProvider;

beforeEach(function () {
    module('myModule');
});

beforeEach(function ($provide) {
    mockInjectedProvider = {
        myFunc: function() {
            return "testvalue"
            }
        }
    };
    $provide.value('injected', mockInjectedProvider );
});

beforeEach(inject(function (_base_) {
    baseProvider = _base_;
}));

it("injectedProvider should be mocked", function () {
    var resultFromMockedProvider = baseProvider.executeMyFuncFromInjected();
    expect(resultFromMockedProvider).toEqual("testvalue");
}); // Here instead of using my mock it executes the actual dependency

In the $provide.value statement I've tried including both injected and injectedProvider, as well as using $provide.provider and mocking a $get function on it but nothing seems to work. I just can't get it to mock away the actual provider. Abstracted base provider looks like this.

(function (ng, module) {
    module.provider("base",
        ["injectedProvider", function (injectedProvider) {
            this.executeMyFuncFromInjected= function() {
                return injectedProvider.myFunc(); // let's say this returns "realvalue"
            }
            this.$get = function () {
                return this;
            };
        }]
    );
})(window.angular, window.angular.module("myModule"));

Everything in my code is working except the Jasmine mocking.

Aucun commentaire:

Enregistrer un commentaire