我有一個包含文本字段的指令,並且我想測試以確保輸入到字段的文本使它成爲模型。如何測試在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