【发布时间】:2014-05-23 22:47:41
【问题描述】:
我正在尝试编写单元测试来测试我的指令。但是,当我单击复选框时,它不会更新模型。
我怎样才能让它改变模型?不知何故,它似乎没有绑定。
当我删除指令并仅使用绑定到范围变量的普通复选框时,会发现与以下相同的行为。 (所以这不是指令的具体问题)
规格功能:
describe('validationGroup directive',function(){
var elm,scope;
beforeEach(function(){
//Create a scope
scope.who = {};
scope.who.selfIncluded = true;
scope.who.othersIncluded = false;
//Compile basic form
inject(function($compile) {
elm = angular.element('<div ng-form="testFormName" validation-group="groupName">' +
'<input id="check1" type="checkbox" atleast-one-insured ng-model="who.selfIncluded" ng-change="update()">' +
'<input id="check2" type="checkbox" atleast-one-insured ng-model="who.othersIncluded"ng-change="update()">' +
'</div>');
elm = $compile(elm)(scope);
});
scope.$digest();
});
//Test the basic form we compiled
it("Should manipulate the model",function(){
var cb0 = elm.find("input").eq(0);
expect(scope.who.selfIncluded).toBeTruthy(); // Succeeds
cb0.triggerHandler('click');
scope.$digest(); // probably not necesarry
expect(scope.who.selfIncluded).toBeFalsy(); // Fails
});
});
【问题讨论】:
-
嗯,我不能说点击不起作用,但您似乎在这里测试角核心功能。点击触发 ng-change,但这与您的应用程序逻辑无关,您不必再次测试。
-
除此之外,还有一个名为 browserTrigger 的实用程序内置在 angular.js 中,它可以模拟事件。你试过吗?
-
指令(代码未在此处发布)中发生了我想要测试的东西。在那段代码正常工作之前,至少基础应该按预期运行。
-
@Narretz browserTrigger 是 angular-scenario.js 的一部分,我只是尝试使用它,它可以工作!谢谢人:)您可能想将其发布为其他阅读此问答的人的可读性答案
标签: angularjs unit-testing angularjs-directive angularjs-scope karma-jasmine