Last active
May 3, 2017 04:42
-
-
Save pswai/ee51b0567f51c39d81c2 to your computer and use it in GitHub Desktop.
AngularJS: Mocking directive for unit test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// With reference to http://stackoverflow.com/a/20951085/605840 | |
// Directives are just factories, so just override your directive | |
// with "Directive" suffix. | |
beforeEach(function () { | |
module(function ($provide) { | |
$provide.factory('starBoxDirective', function () { | |
// Make sure to return an array of objects | |
return [{ | |
// Directive Definition Object | |
}]; | |
}); | |
}); | |
}); |
If you want to use isolate scope bindings, things get way more complicated. Basically, you need to manually replicate the transformations that $compileProvider.directive()
does (1.4.5 source code).
I ended up with this:
$provide.factory('timeRangeInputDirective', function () {
return [{
// This is an internal Directive Definition Object, in the same format that
// $compileProvider.directive() produces.
priority: 0,
index: 0, // used for sorting directives with the same priority
name: 'timeRangeInput',
replace: true,
restrict: 'EA',
templateUrl: "tme-range-input.tpl.html",
scope: {
lsPrefix: '@?localstoragePrefix'
},
$$bindings: {
bindToController: null,
isolateScope: {
lsPrefix: {
attrName: 'localstoragePrefix',
collection: false,
mode: '@',
optional: true
}
}
},
$$isolateBindings: {
lsPrefix: {
attrName: 'localstoragePrefix',
collection: false,
mode: '@',
optional: true
}
},
compile: function () {
return spy_timeRangeInputLink;
}
}];
})
Crazy, huh? But not impossible...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also note that you have to use a compile function in the Directive Definition Object:
If you use only a link function, it won't work, I suppose because Angular's internal code expects a compile function because angular.module().directive(...) transforms the "shortcut" link pattern into the full compile pattern internally.