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/