5

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Yeah, I'd been under this impression as well, since obviously the constructor parameters are already reserved for whatever you put in there yourself... But if my component has calculated fields based on those inputs, how can I tests those properly if I can't use inputs in testing?
Sorry, seems I'd only written half my comment by the time you'd seen it already. In any case, still not sure how to proceed. :(
Seems you're right. I added an example. Sorry for the Dart code, I don't know TS.
Hah. And here I was expecting one would use a different approach during testing. I guess you have a point though -- if you can just do it the same way, why not I guess. :) P.S. For the component I'd barely even notice that's Dart rather than TS/JS, the differences seem kinda subtle.
Yup, syntax difference is subtle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.