这很可能是我不确切知道如何使用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'非常感谢任何帮助!
答案 0 :(得分:1)
不使用空对象作为范围,而是使用:
$scope = $rootScope.$new()
所以你的代码是:
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));