问题描述
限时送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:关键词]
发布评论