应用测试返回“NullInjectorError: No provider for Location!"

编程入门 行业动态 更新时间:2024-10-18 18:15:50
本文介绍了应用测试返回“NullInjectorError: No provider for Location!"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

Appponent.html:

Appponent.html:

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

Headerponent.ts:

Headerponent.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: './headerponent.html',
    styleUrls: ['./headerponent.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();
            }
        }
    }

Appponent.spec.ts:

Appponent.spec.ts:

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

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

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElementponentInstance;
    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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 15:59:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026982.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试   NullInjectorError   provider   Location   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!