Javascript 单元测试:带有动态模板的指令
当我尝试使用一种不寻常的方法获取页面内容的模板时,遇到了一个问题。我已经对其进行了抽象,但只需说代码运行良好,但测试带来了一些问题。我在下面列出了我的指令: 指令:Javascript 单元测试:带有动态模板的指令,javascript,angularjs,unit-testing,Javascript,Angularjs,Unit Testing,当我尝试使用一种不寻常的方法获取页面内容的模板时,遇到了一个问题。我已经对其进行了抽象,但只需说代码运行良好,但测试带来了一些问题。我在下面列出了我的指令: 指令: return { restrict: 'A', scope: { page: '=pageCode', }, link: function (scope, element) { $http.get('templates/' + scope.page + '.html',
return {
restrict: 'A',
scope: {
page: '=pageCode',
},
link: function (scope, element) {
$http.get('templates/' + scope.page + '.html', {cache: $templateCache})
.success(function(html) {
element.replaceWith($compile(html)(scope));
});
}
};
基本上,当使用page code
属性调用该指令时,它会获取该指令并为该页面内容提取特定的部分。我已经尝试模拟出一个$scope
来包含代码,但这不起作用,所以我现在正在硬编码数据页code=“404”
。测试如下:
指令测试:
it('should compile and pass through the scope', function() {
mockDirectiveHtml= '<div data-page-content data-page-code="404"></div>';
mockTemplateHtml= '<h1>Hi</h1>';
$httpBackend.expectGET('templates/404.html').respond(mockTemplateHtml);
pageContentHtml= $compile(mockDirectiveHtml)($scope);
$scope.$digest();
$httpBackend.flush();
expect(pageContentHtml.html()).toEqual('<h1>Hi</h1>');
});
it('应该编译并通过作用域',函数(){
mockDirectiveHtml='';
mockTemplateHtml='Hi';
$httpBackend.expectGET('templates/404.html').respond(mockTemplateHtml);
pageContentHtml=$compile(mockDirectiveHtml)($scope);
$scope.$digest();
$httpBackend.flush();
expect(pageContentHtml.html()).toEqual('Hi');
});
但是,当运行时,控制台告诉我它正在尝试点击GET('templates/undefined.html')
。现在我不确定我的事情是否按正确的顺序进行,或者这是否是解决方案,但过去是否有人遇到过类似的事情?我假设该指令在属性传递给它之前运行,因此在抓取templates/'+'scope.code'
时,该值是未定义的