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

相关内容

热门资讯

一分钟教你!山西扣点子辅助器,... 一分钟教你!山西扣点子辅助器,决战卡五星辅助,细节开挂辅助教程(存在有挂);无需打开直接搜索加薇13...
科技介绍!小逸碰胡脚本,情怀打... 科技介绍!小逸碰胡脚本,情怀打七开辅助,分享开挂辅助教程(有挂方式);无需打开直接搜索打开薇:136...
记者发布!爱来辅助器,杭州都莱... 记者发布!爱来辅助器,杭州都莱破解版,盘点开挂辅助教程(有挂头条);无需打开直接搜索打开薇:1367...
玩家必备科普!钱塘十水三挂件,... 玩家必备科普!钱塘十水三挂件,开心泉州小程序有挂吗,细节开挂辅助教程(新版有挂);无需打开直接搜索薇...
玩家必用!蜀山四川小程序辅助,... 玩家必用!蜀山四川小程序辅助,掌电竞技辅助工具,细节开挂辅助教程(有挂方略);无需打开直接搜索薇:1...
今日科普!闲玩暗宝辅助软件,浙... 今日科普!闲玩暗宝辅助软件,浙江游戏大厅脚本修改,正品开挂辅助教程(有挂方略);无需打开直接搜索加(...
终于知道!小唐家乐园山西辅助软... 终于知道!小唐家乐园山西辅助软件,广西友乐辅助器,关于开挂辅助教程(有挂功能);无需打开直接搜索加薇...
详细说明!福建微乐小程序修改器... 详细说明!福建微乐小程序修改器,小闲川南宜宾辅助,必看开挂辅助教程(竟然有挂);无需打开直接搜索薇:...
关于!微信大a辅助,黑桃a3辅... 关于!微信大a辅助,黑桃a3辅助,正版开挂辅助教程(存在有挂);无需打开直接搜索加(薇:136704...
我来教教大家!蜀渝牌乐汇修改器... 我来教教大家!蜀渝牌乐汇修改器,河洛杠次脚本开发,曝光开挂辅助教程(有挂工具);无需打开直接搜索加薇...