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

相关内容

热门资讯

辅助透视!wepoker怎么提... 辅助透视!wepoker怎么提高运气,pokemmo脚本,举措教程(有挂教学)-哔哩哔哩1)wepo...
揭幕透视!拱趴大菠萝万能挂图解... 揭幕透视!拱趴大菠萝万能挂图解!原来真的是有辅助软件(有挂工具)-哔哩哔哩1、拱趴大菠萝万能挂图解辅...
教你透视!pokemmo脚本,... 教你透视!pokemmo脚本,德普之星有辅助软件吗,课程教程(有挂透明挂)-哔哩哔哩1、下载好德普之...
有挂透视!大菠萝手游辅助!都是... 有挂透视!大菠萝手游辅助!都是真的是有辅助工具(有挂头条)-哔哩哔哩1、操作简单,无需大菠萝手游辅助...
解密透视!智星德州插件,智星菠... 解密透视!智星德州插件,智星菠萝辅助,方案教程(有挂头条)-哔哩哔哩智星菠萝辅助透视方法中分为三种模...
有挂透视!pokemmo手机版... 有挂透视!pokemmo手机版透视脚本!切实是有辅助方法(有挂教程)-哔哩哔哩亲,关键说明,poke...
分享透视!wepoker透视有... 分享透视!wepoker透视有吗!切实是真的有辅助脚本(有挂教学)-哔哩哔哩1、玩家可以在wepok...
解谜透视!wpk私人辅助,wp... 解谜透视!wpk私人辅助,wpk辅助是什么,攻略教程(有挂详情)-哔哩哔哩1、全新机制【wpk辅助是...
曝光透视!werplan有挂吗... 曝光透视!werplan有挂吗!都是是有辅助教程(了解有挂)-哔哩哔哩1、进入游戏-大厅左侧-新手福...
关于透视!hhpoker透视脚... 关于透视!hhpoker透视脚本下载,cloudpoker外开挂,法子教程(真是有挂)-哔哩哔哩1、...