Angular单元测试失败。(Nullinjector错误)
创始人
2024-10-23 22:01:22
0

这个错误通常意味着在测试过程中出现了一个无法注入的依赖项。你需要检查你的测试代码并确保所有的依赖项都被正确注入。以下是一些可能的

  1. 检查你的测试代码和被测试的代码,确保它们之间的依赖关系正确。
  2. 确保你使用了正确的装饰器来注入依赖项。即@Inject或@ViewChild等。
  3. 确保你正确导入依赖项所在的模块。
  4. 如果你在测试环境中使用了Providers,请确保它们包含了被注入的依赖项。
  5. 如果你的代码依赖于服务,请使用createSpyObj或jasmine.createSpy来创建一个模拟对象。

示例代码:

// 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'); }); });

相关内容

热门资讯

wepoke一定有挂!德扑之星... wepoke一定有挂!德扑之星带入记分牌,德州之星手游辅助,辅助教程(有挂教学)是一款可以让一直输的...
WePoKe透视挂!hm3德州... WePoKe透视挂!hm3德州辅助,wepoke用模拟器,细节揭秘(有挂了解)是一款可以让一直输的玩...
WePoKe透视挂!轰趴大菠萝... WePoKe透视挂!轰趴大菠萝十三水有外挂,aapoker软件讲解,曝光教程(有挂介绍),您好,We...
德扑之星有作弊!微扑克有挂,微... 德扑之星有作弊!微扑克有挂,微扑克有稳赢的打法,黑科技教程(有挂方法)1.德扑之星有作弊 ai辅助创...
微扑克wpk透视辅助!wpk微... 微扑克wpk透视辅助!wpk微扑克俱乐部,德州poker有外挂,技巧教程(有挂介绍)1、微扑克wpk...
wepower有外挂!微扑克w... wepower有外挂!微扑克wpk有挂吗,微扑克软件开发,力荐教程(有挂透明)1)wepower有外...
德扑之星有作弊!wepoke怎... 德扑之星有作弊!wepoke怎么来好牌,wpk微扑克真的有辅助,力荐教程(有挂技巧);小薇(透视辅助...
aapoker有猫腻!云扑克有... 您好,aapoker有猫腻这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩...
德州ai机器人!pokerma... 德州ai机器人!pokermaster有外挂吗,wopoker手机辅助,2025新版总结(有挂规律)...
aapoker有挂!wepok... aapoker有挂!wepokeai代打逻辑,微扑克代打,攻略教程(有挂规律),您好,wepokea...