Skip to content

Instantly share code, notes, and snippets.

@pswai
Last active May 3, 2017 04:42
Show Gist options
  • Save pswai/ee51b0567f51c39d81c2 to your computer and use it in GitHub Desktop.
Save pswai/ee51b0567f51c39d81c2 to your computer and use it in GitHub Desktop.
AngularJS: Mocking directive for unit test
// 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
}];
});
});
});
@matthias-ccri
Copy link

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