yearofmoo / ngMidwayTester

118 stars 29 forks source link

Dependency Injection in services #11

Open camposcristian opened 10 years ago

camposcristian commented 10 years ago

I'm trying to figure out the best way to fill a dependency from a service midway test.

// Service

$provide.factory('$dashboard', ['$http', '$userToken', function ($http, userToken1) {

    var url = window.location.host + '/dashboard/',
        files = {},
        userTok = userToken1;

}]);

// Unit test

describe('UnitTest: dashboardService', function () {

var _userToken = 'aUserToken';
var $dashboard;
var $httpBackend;

// load the service's module
beforeEach(function () {
    module('App', 'mockedResources', function ($provide) {
        $provide.value('$userToken', _userToken);
    });
    inject(function ($injector) {
        $dashboard = $injector.get('$dashboard');
        $httpBackend = $injector.get('$httpBackend');
    });
});

// instantiate service
it('should contain an $dashboardService', function () {
    expect($dashboard).not.toBe(null);
});

});

// Midway test

describe('TestDriver: dashboardService', function () {

var _userToken = 'aUserToken',
$dashboard,
tester;

// load the service's module
beforeEach(function () {
    if (tester) {
        tester.destroy();
    }

    tester = ngMidwayTester('App');

    tester.module('App', function ($provide) {
        $provide.value('$userToken', _userToken);
    });
});

it('should contain an $dashboardService', function () {

    tester.module('App', function ($provide) {
        $provide.value('$userToken', _userToken);
    });

    $dashboard = tester.inject('$dashboard');

    expect($dashboard).not.toBe(null);
});

});

Everytime I run grunt test it fails. The error is

Error: Unknown provider: $userTokenProvider <- $userToken <- $dashboard

Any ideas?

jimleroyer commented 9 years ago

+1 same problem here

jimleroyer commented 9 years ago

I've brought a simple modification that introduces a callback function that is called prior to the AngularJS boostrap. Hence I can load any dependencies this way. Might not be the optimal solution but it works, if someone needs the same:

https://www.npmjs.com/package/ng-midway-tester-jlr https://github.com/jimleroyer/ngMidwayTester

The actual changes: https://github.com/jimleroyer/ngMidwayTester/commit/ed176f6d7732c4eac18c0c3677af3941678bc6e4