mardi 12 juin 2018

Angular Testing: provide injected @Attribute in TestBed

I have a component that gets an attribute injected via @Attribute:

@Component({
  selector: 'app-foo',
  templateUrl: './foo.component.html'
})
export class FooComponent implements OnInit {

  constructor(@Attribute('foo') private foo: string) {
    // do something with foo
  }
}

Now I would like to write a test using Jasmine and Karma. Unfortunately I can't find any documentation on how to provide this attribute in the test via the TestBed injector.

This i what I tried:

describe('FooComponent', () => {

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      providers: [
        {provide: 'foo', useValue: 'bar'},
        {provide: Attribute('foo'), useValue: 'bar'},
      ],
      declarations: [FooComponent],
    })
      .compileComponents();
  }));

  it('should merge outer class', () => {
    const fixture = TestBed.createComponent(FooComponent);
    const component = fixture.componentInstance;
    fixture.detectChanges();

    // do actual testing
  });
});

After some research I also defined the following but without success:

Inject('foo')(FooComponent, null, 0);
Attribute('foo')(FooComponent, null, 0);

The parameter passed to the constructro is always null. Does anybody know a solution? I'm using Angular 5.2.10.

Aucun commentaire:

Enregistrer un commentaire