You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目使用Jest跑单元测试报Cannot read property 'injector' of null错误

Angular Jest测试报错TypeError: Cannot read property 'injector' of null解决方案

以下是可直接落地的修复步骤:

  • 修正测试断言逻辑
    现有测试用例中expect(AppComponent).toBeTruthy()写法不符合预期,AppComponent是组件类本身,你需要校验的是实例化后的组件对象,修改为:
it(`should have as title 'Angular-unitTest'`, () => {
  expect(component).toBeTruthy();
  // 若需校验标题可补充以下逻辑
  // expect(component.title).toEqual('Angular-unitTest');
});
  • 补充异步方法await调用
    现有beforeEach中的compileComponents是异步方法,未加await会导致TestBed未完成配置就执行后续组件创建逻辑,修改代码如下:
beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [AppComponent],
    imports: [HttpClientTestingModule],
  }).compileComponents();
});
  • 检查Jest初始化配置
    确认项目根目录的setup-jest.ts文件已正确导入Angular测试必需的依赖,需包含以下内容:
import 'zone.js';
import 'zone.js/testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting(),
  { teardown: { destroyAfterEach: true } }
);
  • 校验依赖版本兼容性
    如果使用Angular 14及以上版本,需保证jest-preset-angular的大版本和Angular版本匹配,同时jest版本不高于29.x,避免API不兼容导致TestBed初始化失败。

内容的提问来源于stack exchange,提问作者Rahil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 22:45:00