AngularJS – 如何在 Jasmine 中为输入事件指令编写单元测试
Posted
技术标签:
【中文标题】AngularJS – 如何在 Jasmine 中为输入事件指令编写单元测试【英文标题】:AngularJS – how to write unit-test in Jasmine for enter events directive 【发布时间】:2014-09-15 16:45:23 【问题描述】:我在 AngularJS 中创建了 enter event 指令,所以我想为该指令运行测试用例。但我不知道如何为输入事件编写代码。
describe('Unit Test: Enter Event', function()
var elm, compile, scope;
beforeEach(function()
module('att.sandbox.attEnterEvent');
inject(function($compile, $rootScope)
compile = $compile;
scope = $rootScope.$new();
);
);
/*scenarion 1*/
it("Enetr Key should call the method inside controller", function()
elm = angular.element('<input type="text" att-enter-event="enterEvent()">');
elm = compile(elm)(scope);
scope.$digest();
scope.enterEvent = jasmine.createSpy();
//**Here i want to add enter event test case**
expect().toHaveBeenCalled();
);
)
【问题讨论】:
你的意思是输入关键事件是吗? 是的..我想为enter evet写测试用例 我真的不明白你的实际查询是什么 @Sprottenwels 我想为输入事件编写 jasmine 测试用例。 你在写单元测试还是e2e测试? 【参考方案1】:最重要的是:
创建事件对象 修改指令 编写测试Create event 并在元素上触发它
var ev = jQuery.Event("keydown",
keyCode: 13
);
el.trigger(ev); // as el is reference to compiled directive
// ---IMPLEMETATION-----------------
angular.module('att.sandbox.attEnterEvent', [])
.directive('hitEnterEvent', function()
return
restrict: 'A',
scope:
hitEnterEvent: '&'
,
link: function(scope, element, attrs)
element.bind("keydown keypress", function(event)
if (event.which === 13 || event.keyCode === 13)
scope.$apply(function()
scope.hitEnterEvent()
);
event.preventDefault();
);
;
)
.controller('hitEntereventCtrl', function($scope)
$scope.showinputtext = false;
$scope.enterEvent = function()
$scope.showinputtext = true;
;
);
// ---SPECS-------------------------
describe('Unit Test: Enter Event', function()
var el, scope;
beforeEach(function()
module('att.sandbox.attEnterEvent');
inject(function($compile, $rootScope)
scope = $rootScope.$new();
el = $compile(angular.element('<input type="text" hit-enter-event="enterEvent()">'))(scope);
);
);
it("Enter key should call the method inside controller", function()
scope.enterEvent = jasmine.createSpy('enterEvent');
var enterKey = jQuery.Event("keydown",
keyCode: 13
);
el.trigger(enterKey);
expect(scope.enterEvent).toHaveBeenCalled();
);
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>
【讨论】:
以上是关于AngularJS – 如何在 Jasmine 中为输入事件指令编写单元测试的主要内容,如果未能解决你的问题,请参考以下文章
在 Jasmine 单元测试中模拟 AngularJS 模块依赖项
在Visual Studio 2013中使用Jasmine + Karma进行AngularJS测试
在 AngularJS/Jasmine 中注入 Mock 服务
AngularJS 指令链接功能在 Jasmine 测试中不运行