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

相关内容

热门资讯

透视辅助!线上德州aapoke... 透视辅助!线上德州aapoker透明挂,aa扑克有外挂好像是有挂(详细挂教程)是一款可以让一直输的玩...
透视辅助!红龙扑克切实是有挂,... 透视辅助!红龙扑克切实是有挂,红龙扑克总是真的有挂(详细辅助工具教程)1、每个玩家都可以进行使用,快...
透视辅助!aApoker好像真... 透视辅助!aApoker好像真的是有挂,aapoker外挂好像存在有挂(详细辅助教程);一、aapo...
三分钟了解!微扑克辅助工具,微... 三分钟了解!微扑克辅助工具,微扑克规律原来有挂(详细有辅助挂教程)1、玩家可以在软件透明挂俱乐部对游...
1.9分钟了解!德扑之星的发牌... 1、1.9分钟了解!德扑之星的发牌是不是有问题,德扑胜率计算果然真的是有挂(详细有辅教程)2、进入游...
黑科技辅助挂!wopoker有... 1、黑科技辅助挂!wopoker有没有外挂,(Wepoke科技)一直是真的有挂(详细辅助德之星教程)...
透视辅助!微扑克竟然真的是有挂... 透视辅助!微扑克竟然真的是有挂,微扑克有辅助挂真是有挂(详细ai机器人教程)1、玩家可以在微扑克有辅...
透视辅助!红龙扑克辅助工具,红... 透视辅助!红龙扑克辅助工具,红龙扑克都是有挂(详细辅助器教程)1、超多福利:超高返利,海量正版游戏,...
WePoKe透明挂!wpeok... WePoKe透明挂!wpeoke软件下载,(wepoke挂)原来真的是有挂(详细辅助有挂教程)1、W...
透视辅助!红龙扑克好像有挂,红... 透视辅助!红龙扑克好像有挂,红龙扑克原来有挂(详细辅助器教程)(1)透视辅助!红龙扑克好像有挂,红龙...