Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Can't test component with templateUrl using TestBed.compileComponent()

I'm trying to get the basics of Angular2 test API and TestBed.compileComponents() is driving me nuts. Either I call it like this:

beforeEach( done => {
  TestBed.configureTestingModule({
    declarations: [MyComponent]
  })
  .compileComponents().then( () => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance();
  });
  done();
});

And then my component is undefined in my test (I believe since compileComponent is async, test is run before my var component gets a value)

Either like that (as describe in documentation):

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

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

But then I get the error: This test module uses the component HomeComponent which is using a "templateUrl", but they were never compiled. Please call "TestBed.compileComponents" before your test.

Can anybody help on this ?

Forget to say I use webpack and RC6

like image 554
theFreedomBanana Avatar asked Oct 03 '16 15:10

theFreedomBanana


2 Answers

Try this:

describe('FooComponent', function () {
    let fixture: ComponentFixture<FooComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [FooComponent]
        });

        fixture = TestBed.createComponent(FooComponent);
        fixture.detectChanges();
    });

You don't need asynchronicity here.

like image 75
R2C2 Avatar answered Sep 29 '22 19:09

R2C2


Try this:

beforeEach( async( () => {
  TestBed.configureTestingModule({
    declarations: [MyComponent]
  })
  .compileComponents().then( () => {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance();
  });
}));
like image 36
Zonkil Avatar answered Sep 29 '22 18:09

Zonkil