这个错误通常意味着在测试过程中出现了一个无法注入的依赖项。你需要检查你的测试代码并确保所有的依赖项都被正确注入。以下是一些可能的
示例代码:
// app.component.ts import { Component, OnInit } from '@angular/core'; import { MyService } from './my.service';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { title = 'my-app'; public msg: string;
constructor(private myService: MyService) {}
ngOnInit() { this.msg = this.myService.getMessage(); } }
// app.component.spec.ts import { TestBed, async } from '@angular/core/testing'; import { AppComponent } from './app.component'; import { MyService } from './my.service';
describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], providers: [MyService] }).compileComponents(); }));
it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); });
it(should have as title 'my-app'
, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('my-app');
});
it(should have a message 'Hello World'
, () => {
const myService = TestBed.inject(MyService);
spyOn(myService, 'getMessage').and.returnValue('Hello World');
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
fixture.detectChanges();
expect(app.msg).toEqual('Hello World');
});
});