Kiara Grouwstra
Kiara Grouwstra

Reputation: 5923

Testing Angular 2 components with @Input

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?

Upvotes: 5

Views: 1634

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657721

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.

Upvotes: 1

Related Questions