Angularjs 使用Angular的单元测试指令时引发的错误
我有一个使用服务的自定义指令。当我运行单元测试时,我不断得到抛出的错误“库在窗口上不存在”。如何避免在单元测试中出现这种错误 示例服务Angularjs 使用Angular的单元测试指令时引发的错误,angularjs,unit-testing,jasmine,Angularjs,Unit Testing,Jasmine,我有一个使用服务的自定义指令。当我运行单元测试时,我不断得到抛出的错误“库在窗口上不存在”。如何避免在单元测试中出现这种错误 示例服务 angular.module('example') .factory('thirdParty', ['$window', function($window) { if (typeof $window.thirdParty === 'undefined') { throw new Error('Library does not exist
angular.module('example')
.factory('thirdParty', ['$window', function($window) {
if (typeof $window.thirdParty === 'undefined') {
throw new Error('Library does not exist on window');
} else {
return $window.thirdParty;
}
}]);
angular.module('example')
.directive('customDirective', ['thirdParty',
function(thirdParty) {
var defaults, link;
link = function(scope, element, attrs, ctrls) {
// do something with thirdParty
};
return {
restrict: 'A',
require: 'ngModel',
link: link,
};
}]);
自定义指令
angular.module('example')
.factory('thirdParty', ['$window', function($window) {
if (typeof $window.thirdParty === 'undefined') {
throw new Error('Library does not exist on window');
} else {
return $window.thirdParty;
}
}]);
angular.module('example')
.directive('customDirective', ['thirdParty',
function(thirdParty) {
var defaults, link;
link = function(scope, element, attrs, ctrls) {
// do something with thirdParty
};
return {
restrict: 'A',
require: 'ngModel',
link: link,
};
}]);
测试
describe('customDirective', function() {
var element, compile, scope;
beforeEach(module('example'));
beforeEach(inject(function($compile, $rootScope) {
compile = $compile;
scope = $rootScope.$new();
}));
// Manually compile and link our directive
function getCompiledElement(template) {
var compiledElement;
var validTemplate = '<input ng-model="example.data" custom-directive />';
compiledElement = compile(template || validTemplate)(scope);
scope.$digest();
return compiledElement;
}
it('should do something', function() {
element = getCompiledElement();
// expects
});
});
description('customDirective',function(){
var元素,编译,作用域;
在每个(模块(“示例”)之前;
beforeach(注入函数($compile,$rootScope){
compile=$compile;
scope=$rootScope.$new();
}));
//手动编译并链接我们的指令
函数getCompiledElement(模板){
var编译元素;
var validTemplate='';
compiledElement=编译(模板| |有效模板)(范围);
范围。$digest();
返回编译元素;
}
它('应该做点什么',函数(){
元素=getCompiledElement();
//期望
});
});
您需要插入$window
(为了更好的度量,也要将其删除)并将第三方的库删除/模拟出来
var $window;
beforeEach(function () {
$window = {};
module('yourmodule', function ($provide) {
$provide.value('$window', $window);
});
$window.thirdParty = {};
});
您需要模拟您的第三方工厂,并在指令测试期间限制对第三方的调用。请参阅以获取更多信息。如果您将第三方工厂条件封装在一个函数中并通过调用该函数来完成任务,那么代码将更易于测试