Angular.js专场

angularjs自动化测试流程

2017-04-18  本文已影响207人  EldonZhao

目录结构:

首先我们来看一下一个project创建好之后,整个工程的目录结构:

web目录结构.png

其中工具会自动生成test目录,其中放置对controllers的单元测试代码,main.js和about.js都是自动生成的。一般情况下,app/scripts/controllers下的每个文件都对应一个测试代码。

代码逻辑:

业务代码:

/**
 * Created by jrzhaoxueyong on 2017/3/8.
 */
'use strict';

angular.module('webApp')
  .controller('LoginCtrl', function ($rootScope, $location, $scope, AuthService) {
    $scope.loginUser = function (credentials) {
      $scope.credentials = {
        username : '',
        password : ''
      };
      console.log('login:', credentials);
      AuthService.login(credentials);
      $location.path('/natgw')
    };

    $rootScope.isUserAuthenticated = function () {
      return AuthService.isAuthenticated();
    }
  });

测试代码:

'use strict';

describe('Controller: LoginCtrl', function () {

  // load the controller's module
  beforeEach(module('webApp'));

  it('should have a method to check user is authenticated', function () {
    // Initialize the controller and a mock scope
    inject(function ($controller, $rootScope, $location) {
      var scope = $rootScope.$new();
      var authService = {
        isAuthenticated: function () {
          return true;
        }
      };
      $controller('LoginCtrl', {
        $scope: scope,
        // place here mocked dependencies
        AuthService: authService,
        $rootScope: $rootScope,
        $location: $location
      });
      expect($rootScope.isUserAuthenticated()).toBe(true);
    });
  });
});

上述是最简单的测试套,针对Controller做相关测试其他如DirectivesFiltersFactories可以参考文章结尾的参考资料。代码样例是验证isUserAuthenticated方法的。下面对这段代码做一个解剖:

执行用例:

至此,整个测试用例就写完了,下面看看运行结果:

Controller\web> grunt test
测试结果.png

参考资料:

上一篇 下一篇

猜你喜欢

热点阅读