web-dev-qa-db-fra.com

Test de l'application Retour "NullInjectorError: Aucun fournisseur de localisation!"

Test d'une application dans Angular 7 avec karma, je ne peux pas supprimer l'erreur dans Subj.

J'ai cherché divers endroits (surtout ici), mais les solutions ne fonctionnent pas ou ne sont pas pertinentes pour mon cas.

App.component.html:

<app-header></app-header>
<router-outlet></router-outlet>

Header.component.ts:

import { Component, OnInit, ViewChild, ElementRef, AfterViewInit, EventEmitter, Output } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';

@Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.less']
})
export class HeaderComponent implements AfterViewInit, OnInit {
    constructor(private location: Location, private router: Router) { 
        setInterval(() => {
            this.now = new Date();
        }, 1000);
    }
...
    onKeyDown(event: KeyboardEvent): void {
        event.preventDefault();
        if (event.which === this.KEY_ESCAPE){
            if (this.router.url !== '/'){
                this.location.back();
            }
        }
    }

App.component.spec.ts:

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { RouterOutlet } from '@angular/router';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        HeaderComponent,
        RouterOutlet
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });
AppComponent should create the app
Error: StaticInjectorError(DynamicTestModule)[HeaderComponent -> Location]: 
  StaticInjectorError(Platform: core)[HeaderComponent -> Location]: 
    NullInjectorError: No provider for Location!
8
Locozade

Une alternative à NullInjectorError: No provider for Location! pendant les tests consiste à importer RouterTestingModule.

ex. mycomponent.spec.ts:

    import { RouterTestingModule } from '@angular/router/testing';
    ...
    beforeEach(() => TestBed.configureTestingModule({
            imports: [ RouterTestingModule ]
    }));
0
NikNik