2013-08-27 89 views
2

我想用茉莉花來測試我的服務,我不斷剛開和「未知提供商:AuthServiceProvider < - AuthService在角/ angular.js在線2683」在軌測試的角度服務

我的服務定義爲:

app.factory('AuthService', ["$resource", "$rootScope", "apiPrefix", function($resource, $rootScope, apiPrefix) { 
    auth_resource = $resource(apiPrefix + "/session", {}, { 
    logout: {method:'GET'} 
    }); 

    var currentUser; 
    return { 
    login: function(email, password, success, failure) { 
     auth_resource.save({}, { 
     email: email, 
     password: password 
     }, function(response){ 
     currentUser = response 
     success() 
     }, function(response){ 
     failure() 
     }); 
    }, 
    logout: function(success, failure) { 
     auth_resource.logout( 
     function(response){ 
      currentUser = undefined 
     }, function(){ 
      $scope.alerts.push({type: "success", msg: "Logged out" }) 
     }, function(){ 
      $scope.alerts.push({type: "error", msg: "Sorry, something went wrong" })   
     } 
    ) 
    }, 
    isLoggedIn: function(){ return currentUser !== undefined}, 
    currentUser: function() { return currentUser; } 
    }; 
}]); 

和我的測試:

describe("AuthService", function(){ 
    var httpBackend; 
    beforeEach(inject(function($httpBackend, AuthService){ 
    module('app'); 

    httpBackend = $httpBackend; 
    AService = AuthService; 
    })); 


    it("should login the user", function(){ 
    // test here 
    }); 
}); 

我的茉莉花配置文件是:

// This pulls in all your specs from the javascripts directory into Jasmine: 
// spec/javascripts/*_spec.js.coffee 
// spec/javascripts/*_spec.js 
// spec/javascripts/*_spec.js.erb 

//= require application 
//= require_tree ./ 

這似乎配置正確,因爲我可以測試我的控制器很好,所以我不知道爲什麼它不能識別我的服務。

回答

1

您可以使用$injector來獲得服務,然後將其注入到實際測試這樣

describe("AuthService", function() { 
    var httpBackend, AService, apiPrefix; 
    beforeEach(module('app')); 

    beforeEach(function() { 
     angular.mock.inject(function ($injector) { 
      httpBackend = $injector.get('$httpBackend'); 

      apiPrefix = angular.mock.module('apiPrefix'); // I assume you have apiPrefix module defined somewhere in your code. 
      AService = $injector.get('AuthService', {apiPrefix: apiPrefix}); 
     }) 
    }); 

    it("should login the user", inject(function (AService) { 
     // test here 
    })); 
}); 

我假設你有地方定義的代碼apiPrefix模塊。

相關問題