2016-04-01 31 views
0

我有依賴於其他服務,從不同的模塊,像這樣一個服務:從不同的模塊中的另一個服務懲戒服務

(function() { 
    'use strict'; 

    angular 
    .module('app.core') 
    .factory('userService', userService); 

    function authService() { 

     return: { 
      userLoggedIn: false 
     } 
    } 

})(); 


(function() { 
    'use strict'; 

    angular 
    .module('app.services') 
    .factory('AuthService', authService); 

    authService.$inject = ['$http', 'userService']; 

    function authService($http, userService) { 
    } 

我想爲我的authService寫測試,但我得到的錯誤注射因爲它無法找到userService

beforeEach(function() { 
    module('app.services'); 
}); 
beforeEach(inject(function(_AuthService_) { 
    authService = _AuthService_; 

})); 

我怎樣才能解決這個問題,將使用$provide幫助我在這裏?

UPDATE

我曾嘗試以下,但仍然得到解決

好的錯誤

beforeEach(function() { 
    module('app.services'); 
}); 

beforeEach(inject(function(_AuthService_, _$provide_) { 
    authService = _AuthService_; 
    $provide = _$provide_; 
})); 

beforeEach(function() { 
    module(function ($provide) { 
     $provide.value('userService', function(){ 
      return { 
       userLoggedIn: false 
      } 
     }); 
    }); 
}); 

,所以我只需要做到以下幾點:

beforeEach(function() { 
    module('app.dataservices'); 
    module(function ($provide) { 
     $provide.value('userService', function(){ 
      return { 
       userLoggedIn: false 
      } 
     }); 
    }); 
}); 

beforeEach(inject(function(_AuthService_) { 
    authService = _AuthService_; 
})); 

測試現在正通過我的

回答

1

假設你的服務使用$state服務,你想模擬身份證。具體爲get方法。那麼你只需要在第一個describe裏面添加這樣的內容。

beforeEach(function() { 
     module(function ($provide) { 
      $provide.service('$state', function() { 
       return { 
        get: function() {} 
       } 
      }); 
    }); 
}); 

this gist您可以使用$provide找到的嘲諷服務的一些有趣的例子。

0

你應該在你的karma.conf.js中預加載所有的服務(我假設你使用的是業力)。

這裏是我們karma.conf.js文件...

/** * 噶測試運行配置 */ '使用嚴格的';

module.exports = function (config) { 
config.set({ 
basePath: './', 
browsers: ['PhantomJS'], 
frameworks: ['jasmine'], 
reporters: ['mocha', 'coverage'], 
singleRun: true, 
preprocessors: { 
    'src/**/!(*spec)*.js': ['coverage'], 
    'dest/**/*.html': ['ng-html2js'] 
}, 
ngHtml2JsPreprocessor: { 
    stripPrefix: 'dest/', 
    moduleName: 'ngHtmlFiles' 
}, 
coverageReporter: { 
    type: 'html', 
    dir: 'coverage' 
}, 
files: [ 
    'dest/vendor.min.js', 
    'bower_components/angular-mocks/angular-mocks.js', 
    'src/**/*.js', 
    'dest/**/*.html' 
] 
}); 
}; 
+0

是的,我的問題是,在我的測試中,我只加載了包含AuthService的'app.services'模塊。但是這個服務依賴於包含在不同模塊中的服務。所以我試圖找到一種方法來提供我的'userService'的模擬版本到'AuthService',而不必在我的測試規範中加載'app.core' – mindparse

相關問題