2016-09-03 80 views
1

我收到如下所示的错误消息。我找不到解决方案。 通过类似的服务模拟。但我不知道它为什么会导致错误。AngularJS/Jasmine undefined不是构造函数

PhantomJS 2.1.1 (Mac OS X 0.0.0) AppBarCtrl $scope.signOut should call firebaseAuth.$signOut FAILED 
TypeError: undefined is not a constructor (evaluating 'firebaseAuth.$signOut()') in app/scripts/controllers/appBar.js (line 19) 
[email protected]/scripts/controllers/appBar.js:19:26 
test/spec/controllers/appBar.js:46:21 
[email protected]://localhost:8080/context.js:151:17 

这些是我的控制器和测试代码。

(function() { 
'use strict'; 

angular.module('authApp') 
    .controller('AppBarCtrl', function($scope, $location, $mdSidenav, firebaseAuth) { 
    $scope.toggleSidenav = function() { 
     $mdSidenav('sidenav').toggle(); 
    }; 

    $scope.signOut = function() { 
     firebaseAuth.$signOut(); 
     $location.path('/'); 
    }; 
    }); 
})(); 

mdSidenav运行良好,但firebaseAuth服务模拟不起作用。 在控制器代码中调用firebaseAuth.$signOut();时,会导致错误。

describe('AppBarCtrl', function() { 
    beforeEach(module('authApp')); 

    var mdSidenav, firebaseAuth; 

    beforeEach(module(function($provide) { 
    mdSidenav = {}; 
    mdSidenav.toggle = jasmine.createSpy('toggle'); 
    $provide.factory('$mdSidenav', function() { 
     return function(componentId) { 
     return mdSidenav; 
     }; 
    }); 
    })); 

    beforeEach(module(function($provide) { 
    firebaseAuth = {}; 
    firebaseAuth.$signOut = jasmine.createSpy('$signOut'); 
    $provide.factory('firebaseAuth', function() { 
     return function() { 
     return firebaseAuth; 
     }; 
    }); 
    })); 

    var $controller; 

    beforeEach(inject(function(_$controller_) { 
    $controller = _$controller_; 
    })); 

    describe('$scope.toggleSidenav', function() { 
    it('should call $mdSidenav.toggle()', function() { 
     var $scope = {}; 
     var controller = $controller('AppBarCtrl', { $scope: $scope }); 
     $scope.toggleSidenav(); 
     expect(mdSidenav.toggle).toHaveBeenCalled(); 
    }) 
    }); 

    describe('$scope.signOut', function() { 
    it('should call firebaseAuth.$signOut', function() { 
     var $scope = {}; 
     var controller = $controller('AppBarCtrl', { $scope: $scope }); 
     console.log(firebaseAuth); 
     $scope.signOut(); 
     expect(firebaseAuth.$signOut).toHaveBeenCalled(); 
    }); 
    }); 
}); 

回答

0

您需要先添加该服务与控制器的情况下

describe('$scope.signOut', function() { 
it('should call firebaseAuth.$signOut', function() { 
    var $scope = {}; 
    var controller = $controller('AppBarCtrl', { $scope: $scope,firebaseAuth:firebaseAuth }); 
    console.log(firebaseAuth); 
    $scope.signOut(); 
    expect(firebaseAuth.$signOut).toHaveBeenCalled(); 
}); 

});

+0

谢谢!有用。但我有1个问题。为什么即使我没有将mdSidenav服务添加到控制器,mdSidenav也能工作? –

+0

,因为它与作用域即$ scope.toggleSidenav相关联,而您正在向控制器注入作用域,而firebaseAuth则不是。 –