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

相关内容

热门资讯

黑科技免费(wpk辅助)外挂透... 黑科技免费(wpk辅助)外挂透视辅助安装(透视)竟然真的有挂(黑科技方法)wpk辅助软件透明挂微扑克...
透视辅助挂(wpK)透视辅助购... 透视辅助挂(wpK)透视辅助购买渠道(黑科技)透视挂使用教程(果然是真的有挂)是一款可以让一直输的玩...
黑科技辅助(wepoke透明黑... 黑科技辅助(wepoke透明黑科技)外挂透视辅助插件(透视)一直是真的有挂(黑科技细节)1、很好的工...
透视安卓版(WPk)透视外挂(... 1、透视安卓版(WPk)透视外挂(黑科技)有透视辅助(好像是有挂);代表性(透视辅助软件透明挂)高科...
黑科技教程(德扑之星软件辅牌器... 黑科技教程(德扑之星软件辅牌器)外挂透视辅助方法(透视)都是真的是有挂(黑科技教程);1)德扑之星软...
攻略辅助(微扑克)辅助手机(辅... 攻略辅助(微扑克)辅助手机(辅助挂)辅助工具(真是是有挂)1、金币登录送、破产送、升级送、活动送。详...
黑科技美元局(wpk发牌逻辑)... 黑科技美元局(wpk发牌逻辑)外挂透明挂辅助方法(透视)一贯是真的有挂(黑科技规律)1)wpk发牌逻...
科普辅助(微扑克)ai机器人(... 科普辅助(微扑克)ai机器人(辅助挂)ai代打(原来存在有挂)1、许多玩家不知道辅助软件怎么退出观战...
黑科技中牌率(wepoke怎么... 黑科技中牌率(wepoke怎么看有没有外挂)外挂透视辅助挂(透视)总是真的是有挂(黑科技技巧)1、游...
黑科技模拟器(WepOke)黑... 黑科技模拟器(WepOke)黑科技ai(黑科技)挂真的假的(真是真的有挂);致您一封信;亲爱玩家:《...