【问题标题】:AngularJS with Karma - how would I write a unit test for the controller带有 Karma 的 AngularJS - 我将如何为控制器编写单元测试
【发布时间】:2017-01-23 23:04:29
【问题描述】:

与代码相同:AngualrJS with Karma - how do I write a unit test for a factory?

我不确定如何为控制器编写单元测试。

有工厂的控制器怎么写,没有工厂怎么写?

【问题讨论】:

    标签: angularjs unit-testing controller karma-jasmine


    【解决方案1】:

    以下是 AngularJS 中的控制器单元测试示例:

    angular.module('myModule', [])
      .controller('myController', function($scope) {
        $scope.num = 2;
        $scope.doSomething = function() {
          $scope.num += 2;
        }
      });
    

    测试:

    describe('myController', function() {
      var $scope;
      beforeEach(function() {
        module('myModule');
        inject(function($controller, $rootScope) {
          $scope = $rootScope.$new();
          $controller('myController', {
            '$scope': $scope
          })
        });
      });
      it('should increment `num` by 2', function() {
        expect($scope.num).toEqual(2);
        $scope.doSomething();
        expect($scope.num).toEqual(4);
      });
    });
    

    我不完全确定您所说的“您将如何使用工厂编写单元测试以及没有工厂如何编写它?”是什么意思。请在评论中解释更多,我会更新这个答案。祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 2014-09-28
      • 1970-01-01
      • 2015-10-03
      • 2016-07-25
      • 1970-01-01
      相关资源
      最近更新 更多