angularjs - Errors thrown when unit testing directive with Angular -
i have custom directive uses service. when run unit tests, keep getting thrown error 'library not exist on window'. how can avoid getting error in unit test?
example service
angular.module('example') .factory('thirdparty', ['$window', function($window) { if (typeof $window.thirdparty === 'undefined') { throw new error('library not exist on window'); } else { return $window.thirdparty; } }]); custom directive
angular.module('example') .directive('customdirective', ['thirdparty', function(thirdparty) { var defaults, link; link = function(scope, element, attrs, ctrls) { // thirdparty }; return { restrict: 'a', require: 'ngmodel', link: link, }; }]); test
describe('customdirective', function() { var element, compile, scope; beforeeach(module('example')); beforeeach(inject(function($compile, $rootscope) { compile = $compile; scope = $rootscope.$new(); })); // manually compile , 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 something', function() { element = getcompiledelement(); // expects }); });
you need inject $window (stub out too, measure) , stub/mock out thirdparty lib.
var $window; beforeeach(function () { $window = {}; module('yourmodule', function ($provide) { $provide.value('$window', $window); }); $window.thirdparty = {}; }); it('throws', function () { delete $window.thirdparty; function fn () { getcompiledelement(); } expect(fn).to.throw(/does not exist on window/i); }); it('just works™', function () { function fn () { getcompiledelement(); } expect(fn).to.not.throw; });
Comments
Post a Comment