我有一个包含文本字段的指令,并且我想测试以确保输入到字段的文本使它成为模型。如何测试在Angularjs中包含文本字段的指令
的指令:
define(function(require) {
'use strict';
var module = require('reporting/js/directives/app.directives');
var template = require('text!reporting/templates/text.box.tpl');
module.directive('textField', function() {
return {
restrict: 'A',
replace: true,
template:template,
scope: {
textField : "=",
textBoxResponses : "="
},
link: function(scope) {
scope.debug = function() {
scope;
// debugger;
};
}
};
});
return module;
});
的标记:
<div ng-form name="textBox">
<!-- <button ng-click="debug()">debug the text box button</button> -->
<h1>Text Box!</h1>
{{textField.label}} <input type="text" name="textBox" ng-model="textBoxResponses[textField.fieldName]">{{name}}
</div>
测试代码:
/* global inject, expect, angular */
define(function(require){
'use strict';
require('angular');
require('angularMock');
require('reporting/js/directives/app.directives');
require('reporting/js/directives/text.box.directive');
describe("builder experimenter", function() {
var directive, scope;
beforeEach(module('app.directives'));
beforeEach(inject(function($compile, $rootScope) {
scope = $rootScope;
scope.textBoxResponses = {};
scope.textBoxField = {
fieldName : "textBox1"
};
directive = angular.element('<div text-field="textBoxField" text-box-responses="textBoxResponses"></div>');
$compile(directive)(scope);
scope.$digest();
}));
it('should put the text box value on the model', inject(function() {
directive.find(":text").val("something");
expect(scope.textBoxResponses.textBox1).toBe("something");
}));
});
});
那么,是什么我想在最后它块做的是模拟在文本字段中输入内容,然后检查以确保文本字段的新值使其成为模型。问题在于模型不会随新值更新。
很好的答案。在'expect()'之前,因为输入指令的事件处理函数将调用包含到'ngModelCtrl。$ setViewValue(txt)'中,所以在'scope'中应用$ apply()就不需要明确的'scope。$ digest ()'按需要 – Nikita