如何使用Jasmine在AngularJS 1.5+组件中测试$ scope。$ on

时间:2018-08-31 21:04:11

标签: javascript angularjs unit-testing jasmine

我试图测试在AngularJS 1.5+组件中使用$ scope。$ on执行了一些代码。我不确定如何在Jasmine中正确设置$ rootScope,以便执行广播。我正在使用this stackoverflow pagethis blog作为参考。这是我的代码。

// Component
(function (app) {
  app.component('demoComponent', {
    controller: ['$scope' function ($scope) {
      $scope.$on('someBroadcast', function (data) {
        // do something with data...
      });
    }]
  });
})(angular.module('demoApp'));


// Jasmine setup
var ctrl, $rootScope, $componentController;

beforeEach(function () {
  module('demoApp');

  inject(function ($rootScope, _$componentController_) {
    ctrl = $rootScope.$new();
    $componentController = _$componentController_('demoComponent', { $scope: ctrl }, null);
  });
});

我的代码在Jasmine设置中的注入功能中崩溃了。有谁知道我需要进行哪些更改才能使其正常工作?

1 个答案:

答案 0 :(得分:0)

由于ctrl是您将在控制器内部使用的作用域,因此您可以执行以下操作:

ctrl.$broadcast('someBroadcast', 'test', 'values, 123);

此外,通常,您将为示波器命名,例如scope$scope,或者事件controllerScopectrl表示该对象是一个控制器,而不是。