应用测试返回“ NullInjectorError:没有位置提供者!”

时间:2019-05-27 11:49:54

标签: unit-testing karma-jasmine angular7

使用Karma在Angular 7中测试应用程序,我无法消除subj中的错误。

我搜索了很多地方(大部分在这里),但是解决方案不起作用或与我的情况无关。

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!

4 个答案:

答案 0 :(得分:5)

在测试过程中,NullInjectorError: No provider for Location!的替代方法是导入RouterTestingModule

例如mycomponent.spec.ts:

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

答案 1 :(得分:5)

就我而言,我已经在使用RouterTestingModule,它不会引发此错误。我从错误的位置导入了位置,因此出现了错误。 “位置”应从此处导入:

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

在您的导入中,您仅应像这样导入RouterTestingModule:

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

然后您可以使用“位置”:

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

别忘了从@ angular / common导入位置

答案 2 :(得分:0)

您可以尝试import> CommonModule

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

答案 3 :(得分:0)

已解决:我只需要导入RouterModule.forRoot([]),这似乎是一个常见错误,因为它修复了许多StaticInjectorError(DynamicTestModule)错误。