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

相关内容

热门资讯

5分钟辅助!红茶馆app辅助,... 5分钟辅助!红茶馆app辅助,小闲川南破解器(透视游戏开挂辅助工具);小闲川南破解器最新版本免费下载...
4分钟辅助!科乐填大坑技巧,微... 4分钟辅助!科乐填大坑技巧,微乐小程游戏破解器下载(透视规律开挂辅助神器);小薇(透视辅助)致您一封...
第七分钟辅助!小程序卡五星辅助... 第七分钟辅助!小程序卡五星辅助,德普之星辅助器(热点推荐开挂辅助神器);1、点击下载安装,小程序卡五...
三分钟辅助!约局吧德州真的存在... 三分钟辅助!约局吧德州真的存在透视吗,微信小程序蜀山四川辅助器(解密关于开挂辅助神器);是一款可以让...
1分钟辅助!wepoker有没... 1分钟辅助!wepoker有没有透视方法,贪玩透视辅助(热点推荐开挂辅助插件);贪玩透视辅助软件透视...
4分钟辅助!越乡游义乌辅助器免... 4分钟辅助!越乡游义乌辅助器免费试用,八闽掌上辅助软件(我来教大家开挂辅助安装);1.八闽掌上辅助软...
第8分钟辅助!四川家园游戏辅助... 第8分钟辅助!四川家园游戏辅助,新道游戏辅助器免费版(透视攻略开挂辅助软件);1、点击下载安装,新道...
5分钟辅助!pokerrrr2... 5分钟辅助!pokerrrr2辅助,闲聚鱼虾蟹软件脚本辅助器(技巧知识分享开挂辅助脚本);AI辅助机...
三分钟辅助!杭州边锋辅助软件,... 三分钟辅助!杭州边锋辅助软件,八张透视辅助(热门推荐开挂辅助安装);杭州边锋辅助软件软件透视开挂是一...
四分钟辅助!wepoker黑侠... 四分钟辅助!wepoker黑侠辅助器正版下载,创思维激k辅助工具(透视辅助开挂辅助插件);大家肯定在...