TypeError: undefined不是一个函数

TypeError: undefined is not a function Angularjs

本文关键字:一个 函数 undefined TypeError      更新时间:2023-09-26

我有一个单元测试,上面的错误一直失败,不确定到底是什么错了,通过错误的外观,它说我需要声明一个函数。有人能指出我的代码有什么问题吗?

单元测试

describe('Test loginService', function() {
var $location, loginService, $scope, authentication, $rootScope;
beforeEach(function() {
    module('app');
    inject(function(_$location_, _$rootScope_, _loginService_,
            _authentication_) {
        $location = _$location_;
        authentication = _authentication_;
        loginService = _loginService_;
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
    });
});
it('Should successfully login with correct credentials', function() {
    $scope.username = 'a@a.com';
    $scope.password = 'a';
    spyOn($location, 'url');
    loginService.login($scope);//Complains about this line
    expect($location.url).toHaveBeenCalled();
    expect($location.url).toHaveBeenCalledWith('/home');
});

登录服务
app.factory('loginService', function(parserService, $location,
    authentication, $rootScope) {
return {
    login : function(scope) {
        parserService.getData().then(function(data) { //This line 
            if (scope.username === data.username
                    && scope.password === data.password) {
                ...
                $location.url("/home");
            } else {
                scope.loginError = "Invalid Credentials";
            }
        });
    }
});

Json文件读取器服务

app.factory('parserService', function($http, $q) {
return {
    getData: function() {
           var deferred = $q.defer();
           $http.get('res/file.json').success(function(data) {
              deferred.resolve(data);
           }).error(function(){
              deferred.reject();
           });
           return deferred.promise;
     }
}
});
错误日志
Chrome 36.0.1985 (Windows 7) Test loginService Should successfully login with correct credentials FAILED
TypeError: undefined is not a function
        at Object.login     (D:../js/services/loginService.js:6:18)
        at null.<anonymous> (D:/../test/unit/loginTest.js:92:16)

既然你不能格式化评论,我用答案…: D

你试过这个吗?

var $location, loginService, $scope, authentication, $rootScope, parserService;
  beforeEach(function() {
  module('app');
  inject(function(_$location_, 
                  _$rootScope_, 
                  _parserService_, 
                  _loginService_, 
                  _authentication_) {
    $location = _$location_;
    authentication = _authentication_;
    loginService = _loginService_;
    $rootScope = _$rootScope_;
    $scope = $rootScope.$new();
    parserService = _parserService_;
  });
});