I'm trying to test my Angular 2 components, instantiating with new MyComponent()
. However, for components that take @Input
s, how might I pass those in? Then, if instantiated, say I'd like to change an input. Is that just a matter of reassigning to the variable I'd passed in?
If you create an instance with new
there is nothing else you can do to assigning to the field. You can use the TestComponentBuilder
to get change detection and binding.
Below a Dart code example which tests a BwuArraySelector
component.
I assume you can figure out how to do it in TS.
/// Component only for testing BwuArraySelector
@Component(
selector: 'test-cmp-singleconfigured',
directives: const [BwuArraySelector],
template: '''
<bwu-array-selector #singleConfigured
[items]='[{"name": "one"},{"name": "two"},{"name": "three"}]'>
</bwu-array-selector>
''')
class SingleConfigured {
@ViewChild('singleConfigured') BwuArraySelector arraySelector;
}
...
// inject the TextComponentBuilder and create a component instance
ngTest('single selection', (TestComponentBuilder tcb) async {
ComponentFixture tc = await tcb.createAsync(SingleConfigured);
tc..detectChanges();
BwuArraySelector el =
(tc.componentInstance as SingleConfigured).arraySelector;
The call to detectChanges()
initializes the inputs of BwuArraySelector
with the values from the SingleConfigured
test components template bindings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With