Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Angular 2 components with @Input

Tags:

angular

I'm trying to test my Angular 2 components, instantiating with new MyComponent(). However, for components that take @Inputs, 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?

like image 425
Kiara Grouwstra Avatar asked Nov 09 '22 22:11

Kiara Grouwstra


1 Answers

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.

like image 52
Günter Zöchbauer Avatar answered Nov 15 '22 08:11

Günter Zöchbauer