【问题标题】:App testing return "NullInjectorError: No provider for Location!"应用程序测试返回“NullInjectorError: No provider for Location!”
【发布时间】:2019-05-27 11:49:54
【问题描述】:

使用 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!

【问题讨论】:

    标签: unit-testing karma-jasmine angular7


    【解决方案1】:

    在我的例子中,我已经在使用 RouterTestingModule,它不应该引发这个错误。我从错误的地方导入了位置,所以出现了错误。 'Location' 应该从这里导入:

    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】:

    修复它:我需要做的就是导入RouterModule.forRoot([]),这似乎是一个常见错误,因为它修复了很多StaticInjectorError(DynamicTestModule) 错误。

    【讨论】:

    • 可以扩展您的答案并解释哪个文件需要此导入?
    • 到规范文件导入。
    【解决方案3】:

    测试期间NullInjectorError: No provider for Location! 的替代方法是导入RouterTestingModule

    例如。 mycomponent.spec.ts:

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

    【讨论】:

      【解决方案4】:

      你可以试试import > CommonModule

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

      【讨论】:

        猜你喜欢
        • 2019-01-24
        • 2022-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-10
        • 2021-06-01
        • 2018-10-14
        • 2021-10-16
        相关资源
        最近更新 更多