2

我正在尝试使用 jasmine 测试我的服务,并且我一直保持入门和“未知提供者:AuthServiceProvider <- 第 2683 行的 angular/angular.js 中的 AuthService”

我的服务定义:

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 ./

这似乎配置正确,因为我可以很好地测试我的控制器,所以我不确定它为什么不能识别我的服务。

4

1 回答 1

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 模块。

于 2013-08-27T04:19:34.430 回答