应用测试返回“NullInjectorError: No provider for Location!" [英] App testing return "NullInjectorError: No provider for Location!"

查看:12
本文介绍了应用测试返回“NullInjectorError: No provider for Location!"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.component.html:

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

Header.component.ts:

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:

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!

推荐答案

Fixed it: All I need to do is import RouterModule.forRoot([]), 这似乎是一个常见的错误因为它修复了很多 StaticInjectorError(DynamicTestModule) 错误.

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.

这篇关于应用测试返回“NullInjectorError: No provider for Location!"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆