用注入服务对angular控制器进行单元测试

Unit test angular controller with injected service

本文关键字:单元测试 控制器 angular 注入 服务      更新时间:2023-09-26

在测试LoginController

时获得列出的错误

LoginController.js

'use strict';
/*Login Module Controllers */
angular.module('loginModule.controller', ['myApp.services', 'ngMd5']).
controller('LoginController', ['$scope', '$location', 'ajaxService', 'userPersistenceService', 'md5', 'toast',
function($scope, $location, ajaxService, userService, md5, toast) {
    $scope.username = '';
    $scope.password = '';
    $scope.loginSuccess = '';
    $scope.login = function() {
        ajaxService.ajaxPostReq({username: $scope.username, password: md5.createHash($scope.password || '')}, 'http://localhost:3000/user/auth', successFunction, errorFunction);
    }
    function successFunction(response) {
        if(response.status == 'success') {
            $scope.loginSuccess = true;
            userService.setUser({userName: response.username, sessionId: response.sessionId});
            $location.path('/home');
            toast.showMessage('Successfully Logged In', response.status);
        } else {
            errorFunction(response);
        }
    }
    function errorFunction(response) {
        $scope.loginSuccess = false;
        toast.showMessage(response.error, response.status);
    }
}]);

LoginController.test.js

describe('Controller: LoginCtrl', function() {
    angular.mock.module('loginModule.controller', []);
    angular.mock.module('myApp.services', []);
    var ctrl, ajaxService, $q;
    beforeEach(inject(function($controller, _$q_, _ajaxService_){
        ctrl = $controller('LoginController');
        $q = _$q_;
        ajaxService = _ajaxService_;
    }));
    describe('Login function', function() {
        beforeEach(function(){
            var deferred = $q.defer();
            spyOn(ajaxService, 'ajaxPostReq').and.returnValue(deferred.promise);
            ctrl.login();
        });
        it('should call ajaxService', function() {
            expect(ajaxService.ajaxPostReq).toHaveBeenCalled();
        });
    });
});

如何正确测试LoginController ??使用如上所述的代码,我在单元测试时得到以下错误:

 Chrome 53.0.2785 (Mac OS X 10.12.0) Controller: LoginCtrl Login function should call ajaxService FAILED
 Error: [$injector:unpr] Unknown provider: ajaxServiceProvider <- ajaxService
 http://errors.angularjs.org/1.5.6/$injector/unpr?p0=ajaxServiceProvider%20%3C-%20ajaxService
 at client/app/lib/angular/angular.js:68:12
 at client/app/lib/angular/angular.js:4501:19
 at Object.getService [as get] (client/app/lib/angular/angular.js:4654:39)
 at client/app/lib/angular/angular.js:4506:45
 at getService (client/app/lib/angular/angular.js:4654:39)
 at injectionArgs (client/app/lib/angular/angular.js:4678:58)
 at Object.invoke (client/app/lib/angular/angular.js:4700:18)
 at Object.workFn (client/app/lib/angular/angular-mocks.js:3071:20)
 Error: Declaration Location
 at window.inject.angular.mock.inject (client/app/lib/angular/angular-mocks.js:3033:25)
 at Suite.<anonymous> (client/test/LoginModule/LoginController.js:6:20)
 at client/test/LoginModule/LoginController.js:1:5
 TypeError: Cannot read property 'defer' of undefined
 at Object.<anonymous> (client/test/LoginModule/LoginController.js:13:34)
 TypeError: Cannot read property 'ajaxPostReq' of undefined
 at Object.<anonymous> (client/test/LoginModule/LoginController.js:19:35)
 Chrome 53.0.2785 (Mac OS X 10.12.0): Executed 6 of 6 (1 FAILED) (0 secs / 0.07 secs)
 Chrome 53.0.2785 (Mac OS X 10.12.0): Executed 6 of 6 (1 FAILED) (0.007 secs / 0.07 secs)  

你不是bootstrapping你是module

beforeEach(module('myApp'));

并检查您是否已将您的服务包含在karma.conf.js

files: [
  'app/bower_components/angular/angular.js',
  'app/bower_components/angular-mocks/angular-mocks.js',
  'app/bower_components/angular-ui-router/release/angular-ui-router.js',
  'app/app.js',
  'app/controllers/*.js',
  'app/services/*.js',
  'tests/**/*.js'
],