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

相关内容

热门资讯

透视工具!aapoker安装包... 透视工具!aapoker安装包怎么使用(透视)aapoker万能辅助器,AA德州教程(有挂揭秘)1、...
透视数据!aapoker辅助工... 透视数据!aapoker辅助工具安全吗(透视)aapoker插件,安装教程(有挂细节);1、这是跨平...
透视总结!aapoker怎么设... 透视总结!aapoker怎么设置提高好牌几率(透视)aapoker辅助器是真的吗,解密教程(有挂揭秘...
透视系统!aapoker如何设... 透视系统!aapoker如何设置胜率(透视)aa poker透视软件,2025新版教程(有挂解说)1...
透视挂!aapoker辅助器怎... 透视挂!aapoker辅助器怎么用(透视)aapoker ai插件,解密教程(有挂揭秘)1.aapo...
透视中牌率!aa poker透... 透视中牌率!aa poker透视软件(透视)aapoker透视插件,解密教程(有挂解说)1、操作简单...
透视规律!aapoker免费透... 透视规律!aapoker免费透视脚本(透视)aapoker插件下载,AI教程(有挂揭秘)1、aapo...
透视新版!aapoker辅助工... 透视新版!aapoker辅助工具安全吗(透视)aapoker万能辅助器,教你攻略(有挂黑科技)1、构...
透视系统!aapoker安装包... 透视系统!aapoker安装包怎么使用(透视)aapoker透视插件,解说技巧(有挂细节)小薇(透视...
透视透视!aapoker俱乐部... 透视透视!aapoker俱乐部靠谱吗(透视)aapoker俱乐部靠谱吗,黑科技教程(有挂细节);1、...