【发布时间】:2014-10-24 09:33:58
【问题描述】:
我正在尝试在一个非常简单的角度指令中对数据绑定进行单元测试:
指令
<uri></uri>
.directive('uri', function () {
return {
restrict: 'E',
templateUrl: 'views/partials/directives/uri.html',
transclude: false,
replace: false,
scope: false,
controller: function ($scope) {
$scope.uri = null;
}
};
});
模板
<h2>url</h2>
<input type="text" placeholder="{{uri}}" class="form-control" ng-readonly="true">
单元测试
describe('Directive: uri', function () {
// we declare some global vars to be used in the tests
var elem,
scope,
$compile,
directive = angular.element('<uri></uri>'),
template = 'views/partials/directives/uri.html';
// load the module / template we want to test
beforeEach(module('app', template));
// before each test, creates a fresh scope
beforeEach(inject(function ($rootScope, _$compile_, $templateCache) {
//assign the template to the expected url called by the directive and put it in the cache
var tplCache = $templateCache.get(template);
$templateCache.put(template, tplCache);
console.log(tplCache);
scope = $rootScope.$new();
$compile = _$compile_;
}));
function compileDirective() {
//create the element with the directive template
elem = $compile(directive)(scope);
scope.$digest();
}
it('should set the input value to the scope.uri value', function () {
// add uri to scope
var uri = 'test-uri';
scope.uri = uri;
// then produce our directive using it
console.log(scope.uri);
compileDirective();
console.log(scope.uri);
console.log(elem);
// this should impact the input value value
var templateAsHtml = elem.html();
expect(templateAsHtml).toContain(scope.uri);
});
});
templateCache 缓存模板。 使用提供的指令在范围内编译元素。 但不知何故 uri 属性没有链接到我的指令。此外,在 scope.$digest() 之后 scope.uri 为空...
业力测试结果
LOG: '<h2>url</h2>
<input type="text" class="form-control" placeholder="{{uri}}" ng-readonly="true">'
LOG: 'test-uri'
LOG: null
LOG: Object{0: <uri class="ng-scope"><h2>url</h2>
<input type="text" class="form-control" placeholder="" ng-readonly="true" readonly="readonly"></uri>, length: 1}
PhantomJS 1.9.7 (Mac OS X) Directive: uri should set the input value to the scope.uri value FAILED
Expected '<h2>url</h2>
<input type="text" class="form-control" placeholder="" ng-readonly="true" readonly="readonly">' to contain null.
PhantomJS 1.9.7 (Mac OS X): Executed 6 of 6 (1 FAILED) (0.03 secs / 0.026 secs)
Warning: Task "karma:unit" failed. Use --force to continue.
Aborted due to warnings.
【问题讨论】:
-
能否包含您的指令定义?
-
嗯,谢谢 Cathal... 你看,我的指令初始化为 uri = null。这会覆盖我在摘要循环中的测试。呵呵……
标签: javascript angularjs unit-testing data-binding