11

Say I have an Angular 2 Component with two input parameters:

@Component{... (omitted for clarity)}
export class SomeComponent {

@Input() a: number
@Input() b: number

}

When I want to test this component I have something like:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        SomeComponent,
      ],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

The createComponent call does not take any parameters or allow me to call the constructor. How can I instantiate/test the component for various number values?

4
  • 2
    component.a = 1; component.b = 2; ? Commented Mar 7, 2017 at 7:52
  • 1
    That would alter the value after instantiation. This would cause the templates of the html to use the constructor values which are (default) 0 at that time. Commented Mar 7, 2017 at 7:58
  • 1
    That's the only way to set these values. You can't change the fields of an object without first constructing the object. And you can do that before calling fixture.detectChanges(). Commented Mar 7, 2017 at 7:59
  • My previous comment is not completely true: The templates do get the values set in the component in the way @JBNizet suggested. It made my tests pass. Thanks! Could you convert it in an answer so that i can accept it? Commented Mar 7, 2017 at 8:38

1 Answer 1

4

As pointed ou by JB Nizet, when a component has @input parameters, you need to init them in the beforeEach() : ```

beforeEach(() => {
    fixture = TestBed.createComponent(SomeComponent);
    component = fixture.componentInstance;
    component.a = 1;
    component.b = 2;
    fixture.detectChanges();
});

```

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

2 Comments

const injector = Injector.create({providers: [{provide: SelfService, useClass: MockSelfService, deps: []}]}); component.selfService = injector.get(SelfService); If SelfService depends on http for example one can create it via injector
All these actions happen after createComponent() is called. So it will work after constuctor finishes. Therefore, you will not be able to set readonly properties.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.