1

I am trying to test one of my components using Jasmine and Karma and it fails with the following error = "Error in app/components/login.js class LoginComponent_Host - inline template:0:0 caused by: Bootstrap at least one component before injecting Router".

The same kind of test works without any issues for our root component. Here is the test code -

import { LoginComponent } from './login';
import { TestBed, async } from '@angular/core/testing';
import { AppModule } from "../app.module";
import { APP_BASE_HREF } from "@angular/common"

describe('LoginComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ AppModule ],
      providers: [ { provide: APP_BASE_HREF, useValue : '/' } ]
    });
  });

  it('should instantiate component', async(() => {
    TestBed.compileComponents().then(() => {
      let fixture = TestBed.createComponent(LoginComponent);
      fixture.detectChanges();
      expect(fixture.componentInstance instanceof LoginComponent).toBe(true, 'should create LoginComponent');
    });
  }));
});

LoginComponent is part of AppModule and here is how AppModule is setup:

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing
  ],
  declarations: [
    AppComponent,
    LoginComponent,
    SponsorsComponent
  ],
  providers: [
    AuthenticationService,
    UserService
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

The same test works without any issues for AppComponent which is the root component of the AppModule. Wondering if there is any testbed setup that needs to be done to bootstrap AppComponent ? Please let me know if there are any suggestions that I could try. Thanks in advance.

Naren Nala
  • 165
  • 2
  • 9
  • having the same issue and similar question on here, answer provided also: http://stackoverflow.com/questions/39902606/angular2-2-0-0-component-unit-test-causes-error-bootstrap-at-least-one-componen?rq=1 – sitesbyjoe Oct 07 '16 at 16:57
  • I am not using any routing module as part of my test though. routing is only part of my module. So, not sure how I can leverage the solution suggested in that post. Just being curious, were you able to fix yours using the suggestion given in that post ? – Naren Nala Oct 08 '16 at 20:53
  • You don't need to actually mock the routes. Just have the imports like this: `imports: [AppModule, RouterTestingModule]`. You shouldn't even need to provide the APP_BASE_HREF when you do that. – František Žiačik Oct 23 '16 at 12:35

0 Answers0