Make controllers used with a bindToController directive easier to test
There doesn't seem to be a clear mechanism of unit-testing a controller that's used in a directive with bindToController: true. These controllers assume certain properties being set before the execution of the constructor.
I could build a mechanism myself using a temporary constructor etc. but it would be nice to have something in Angular itself.
I discovered the private boolean arg later in the $controller service that serves the purpose:
ctrlFn = $controller(MyCtrl, {
$scope: scope,
}, true):
ctrlFn.instance.foo = "bar";
ctrl = ctrlFn();
Would you consider making that flag public and thus officially supported? Or maybe add a helper to angular mock?
See also this Stack Overflow question.
In Angular 2.0, how will components initialize based on property bindings (when necessary)? Will property bindings be available as constructor parameters somehow, or will some component initialization need to occur after the constructor call completes?
This concept is very important for cases like:
<my-component [read-only]="true" [make-color]="blue" />
Highly useful to use attribute bindings, property bindings, etc to allow customization of the component by the consumer.
Sorry, probably a bit off topic here, but very related to the use case that caused this issue.
Fantastic, thanks!
:+1:
:+1: This is what it was meant to be.
:+1:
+1
@ernestoalejo
What is someId?
in the snippet.
newScope = element.isolateScope();
ctrl = newScope.someId;
``
@lokeshjainRL I copied it from the other comment. Anyway this issue was closed later with a much easier approach:
describe('buttons.RemoveButtonCtrl', function () {
var ctrl, $scope;
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('xxCtrl', {
$scope: scope,
}, {
label: 'foo'
});
}));
it('should have a label', function () {
expect(ctrl.label).toBe('foo');
});
});
(from http://stackoverflow.com/questions/25837774/bindtocontroller-in-unit-tests)
Pass the initial scope you want to test defaults against as the third argument to $controller.
@ernestoalejo Thanks for pointing to the resources. But this approach is not when you have complex html with it when you need access to the input element and forms. I prefer solution from your comment.
I Figured that someId.
In directive definition
return{
bindToController:{
},
scope:{},
controller: 'directiveController',
controllerAs; 'someId'
}
That controllerAs attribute is the someId. in Your comment.