我有一个简单的指令:
'使用严格';
angular
.module('app')
.directive('ngEmailMask', ngEmailMask);
function ngEmailMask() {
var directive = {
replace: true,
restrict: 'EA',
scope: {
user: '@',
host: '@'
},
template: '<a href="mailto:{{user}}@{{host}}">{{user}}@{{host}}</a>'
};
return directive;
}
我正在编写 Karma 单元测试来检查指令输出正确的 HTML。到目前为止我已经得到了这个:
describe('ngEmailMask', function() {
// Bindable members
var $compile,
$rootScope;
// Load module
beforeEach(angular.mock.module('app'));
// Bind injected references to local variables
beforeEach(inject(function(_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
// Verify service returns
it('Replaces the tag with the correct HTML', function() {
// Compile element
var element = $compile('<ng-email-mask data-user="test" data-host="gmail.com"></ng-email-mask>')($rootScope);
// Evaluate scope
$rootScope.$digest();
console.log(element.html());
});
});
我按照 Angular 网站 here 上的示例进行操作但我上面的例子返回一个错误:
错误:意外请求:GET/app/home/home.html
该路径与指令无关,并且可能会发生变化(这与我正在使用的 UI Router 中的状态和路由有关)。那么如何测试这个指令而不看到这些关于不同文件的错误呢?
最佳答案
您必须预期 jasmine 测试中的所有 XHR 调用(甚至模板)。最简单的方法是在运行测试之前将所有模板添加到 templateCache 中。
关于javascript - Angular 指令的 Karma 测试返回意外请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39367426/