角度指令给出的Karma测试错误:$ sce:insecurl
问题描述:
我正在为一个称为日历星期的指令编写一个测试,并且出现以下角度错误:https://docs.angularjs.org/error/ $ sce/insecurl?p0 = http:%2F%2Fhere。 COM%2Fviews%2Fdirectives%2FcalendarWeek.html
我的规格已经
describe('Tests for CalendarWeek Directive', function(){
var el, scope, controller;
beforeEach(function() {
module('MyApp');
return inject(function($injector, $compile, $rootScope, $httpBackend, $sce) {
el = angular.element("<div calendar-week></div>");
$compile(el)($rootScope.$new());
$rootScope.$digest();
controller = el.controller("calendarWeek");
$sce.trustAsResourceUrl("http://here.com/views/directives/calendarWeek.html")
$httpBackend.whenGET("http://here.com/views/directives/calendarWeek.html").respond({ hello: 'World' });
有我丢失的东西?
答
从Angular docs: 默认情况下,Angular只加载来自与应用程序文档相同的域和协议的模板。这是通过调用模板URL上的$ sce.getTrustedResourceUrl来完成的。要从其他域和/或协议加载模板,您可以将其列入白名单或将其包装为可信值。
您正试图从不同的域或不同的协议加载资源。我认为你需要包装一下你的URL是这样的:
$httpBackend.whenGET($sce.trustAsResourceUrl("http://here.com/views/directives/calendarWeek.html")).respond({ hello: 'World' });
或者白名单这样的:
angular.module('myApp', []).config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
// Allow same origin resource loads.
'self',
// Allow loading from our assets domain.
'http://here.com/views/directives/calendarWeek.html'
]);
});
为什么在测试指令你测试服务器的请求?该指令只应该操纵DOM,这是应该测试的。分别测试从服务器请求数据的资源 –
如果您按照错误消息中的链接进行操作,您将完全看到缺少的内容:从不可信来源处理资源被阻止。 Angular阻止你加载不安全的资源:https://docs.angularjs.org/api/ng/service/$sce –