$ EMIT使用testacular时产生一个错误(因缘)因缘、错误、EMIT、testacular

2023-09-13 04:27:39 作者:寂寞如风

这是最有可能我不知道究竟如何使用噶。说我有一个angularJS样板测试,像这样结果

This is most likely me not knowing exactly how to use Karma. Say I have an angularJS boilerplate test like so


'use strict';

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

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

  var MainCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller) {
    scope = {};
    MainCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings.length).toBe(3);
  });
});

如果我插入一个$在我的控制器发出像这样结果

if I insert an $emit in my Controller like so


'use strict';

angular.module('testingApp')
  .controller('MainCtrl', function ($scope) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];

    $scope.$emit('helloWorld');
  });

我现在测试失败,并说:

My test now fails and says

TypeError: Object # has no method '$emit'

任何帮助很多AP preciated

Any help is much appreciated!

推荐答案

,使用:

$scope = $rootScope.$new()

所以你的code将是:

So your code would be:

// Initialize the controller and a mock scope
  beforeEach(inject(function ($controller) {
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));