App testing return “NullInjectorError: No provider for Location!”

我只是一个虾纸丫 提交于 2021-01-22 05:18:09

问题


Testing an app in Angular 7 with Karma, I can't remove the error in subj.

I have searched various places (mostly here) but either the solutions don't work or are not relevant to my case.

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!

回答1:


Fixed it: all I needed to do was to import RouterModule.forRoot([]), which seems to be a common mistake as it fixes a lot of StaticInjectorError(DynamicTestModule) errors.




回答2:


In my case, I was using the RouterTestingModule already which should not raise this error. I have imported Location from the wrong place so the error has appeared. 'Location' should be imported from here:

import {Location} from '@angular/common';

In your imports you should only import RouterTestingModule like this:

TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes(
          [
            {path: 'add', component: DummyComponent, pathMatch: 'full'}
          ]
        )
      ],

and then you can use Location like this:

it('Should navigate to / before + button click', () => {
    const location: Location = TestBed.get(Location);
    expect(location.path()).toBe('');
  });

Just don't forget to import Location from @angular/common




回答3:


An alternative to NullInjectorError: No provider for Location! during the testing is to import RouterTestingModule.

ex. mycomponent.spec.ts:

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



回答4:


Can u try to import > CommonModule

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


来源:https://stackoverflow.com/questions/56325514/app-testing-return-nullinjectorerror-no-provider-for-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!