angularjs - 如何测试由事件执行的 Controller 范围内的函数

标签 angularjs unit-testing jasmine karma-jasmine

Controller 中的功能:

angular.module('myApp').controller('MyController', function(){

   $scope.f = function($event){
      $event.preventDefault();
      //logic
      return data;
   }
})

describe('MyController', function(){
    'use strict';
    var MyController,
        $scope;

    beforeEach(module('myApp'));

    beforeEach($inject(function($rootScope, $controller){
       $scope = $rootScope.$new();
       MyController = $controller('MyController', {
          $scope: $scope
       })
    }));
})
it('should...', function(){
    //fire event and expect data
})

$scope.f 函数用于指令中,可以通过 ng-click="f($event)"

执行

单元测试中火灾事件的正确方法是什么?

最佳答案

简答

您不需要触发该事件。您可以访问具有您要测试的功能的范围。这意味着您只需执行该函数,然后断言。它看起来像这样:

it('should call preventDefault on the given event', function(){
  var testEvent = $.Event('someEvent');
  $scope.f(testEvent);
  expect(testEvent.isDefaultPrevented()).toBe(true);
});

请参阅以下内容:

完整规范

此外 - 您的 it block 应该位于您的 describe block 内,以便它可以访问 $scope 字段。它应该看起来更像这样:

describe('MyController', function(){
  'use strict';
  var MyController,
      $scope;

  beforeEach(module('myApp'));

  beforeEach($inject(function($rootScope, $controller){
    $scope = $rootScope.$new();
    MyController = $controller('MyController', {
      $scope: $scope
    })
  }));

  it('should call preventDefault on the given event', function(){
    var testEvent = $.Event('someEvent');
    $scope.f(testEvent);
    expect(testEvent.isDefaultPrevented()).toBe(true);
  });
})

关于结构的注释

不要害怕使用describe block 来构建您的测试。假设您在 $scope 上有另一个名为 f2 的函数,那么您可能希望像这样对规范文件进行分区:

describe('MyController', function(){
  'use strict';
  var MyController,
      $scope;

  beforeEach(module('myApp'));

  beforeEach($inject(function($rootScope, $controller){
    $scope = $rootScope.$new();
    MyController = $controller('MyController', {
      $scope: $scope
    })
  }));

  describe('$scope', function() {
    describe('.f()', function() {
      // tests related to only the .f() function
    });

    describe('.f2()', function() {
      // tests related to only the .f2() function
    });
  });
})

这样做的好处是,当测试失败时,您看到的错误消息是基于 describe block 的层次结构构建的。所以它会是这样的:

MyController $scope .f() should call preventDefault on the given event

关于angularjs - 如何测试由事件执行的 Controller 范围内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39250216/

相关文章:

objective-c - 如何使用 Kiwi 异步测试委托(delegate)

unit-testing - 在angularjs中测试指令时如何模拟模糊?

java - java中如何解密字符串

angularjs - 从 ng-content 引用组件变量

Angularjs指令: accessing sibling elements in link function

unit-testing - VS 2013 MSTest 与 nUnit 与 xUnit

java - 使用 spring.Headache 使用 hibernate genericdao 模式测试 dao

javascript - 有什么方法可以将 Specflow 与 Jasmine 集成?

backbone.js - BackboneJS 测试集合获取

javascript - 使用 $scope.apply() 后点击展开不工作