Skip to content

Fix Angular 2 Tests with Karma

March 1st, 2017 - Software(1 min)

Below are some fixes I had to apply in order to make Angular 2 tests work with karma.

Binding

  • Error: Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’

  • Solution: Import FormsModulein your test:

    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [FormsModule]
    })

Unknown component

  • Error: ‘custom-component’ is not a known element

  • Solution: Declare the component in your test:

    TestBed.configureTestingModule({
      declarations: [
        MyComponent,
        CustomComponent // The component declared in the template
      ]
    })

Note: If the element is in another module, then import the other module (like in the previous case) instead of declaring elements one by one.

Unknown <router-outlet> tag

  • Error: ‘router-outlet’ is not a known element

  • Solution: Import RouterTestingModule:

    import { RouterTestingModule } from '@angular/router/testing'
    
    // ...
    
    TestBed.configureTestingModule({
      declarations: [AppComponent, OtherComponent],
      imports: [RouterTestingModule]
    })

Note: This list contains issues I’ve encountered. Please feel free to send me more.

HTH,

Share on
Reddit
Linked in
Whatsapp

A little experiment: