首页 文章

使用testacular(业力)时$ emit会产生错误

提问于
浏览
0

这很可能是我不知道如何使用Karma . 假设我有一个angularJS样板测试

'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);
  });
});

如果我在我的控制器中插入$ emit就像这样

'use strict';

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

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

我的测试现在失败并说

TypeError: Object # has no method '$emit'

非常感谢任何帮助!

1 回答

  • 1

    不使用空对象作为范围,而是使用:

    $scope = $rootScope.$new()
    

    所以你的代码是:

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

相关问题