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

Angular单元测试:构造函数引入Globals.ts时如何创建组件实例

故障原因

你的Login组件构造函数声明了两个注入依赖:Globals 和 AppService,但在TestBed的providers配置中仅注册了AppService,Angular依赖注入器无法解析Globals实例,导致组件初始化失败,最终实例为undefined。

修复方案

根据你的测试需求,可以选择以下两种方式配置:

方式1:直接注册真实的Globals实例

如果测试逻辑需要依赖Globals的真实实现,直接将Globals添加到providers数组即可:

import { Globals } from '你的Globals文件相对路径'; // 替换为实际文件路径

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports:[
        FormsModule,
        ReactiveFormsModule,
      ],
      providers:[
        AppService,
        Globals // 新增Globals注册
      ]
    })
    .compileComponents();
  }));
   beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

方式2:注册Mock的Globals实例(单元测试更推荐)

单元测试推荐隔离外部依赖,仅验证LoginComponent本身的逻辑,因此可以用模拟对象替代真实的Globals,避免Globals的内部逻辑影响测试结果:

import { Globals } from '你的Globals文件相对路径'; // 替换为实际文件路径

// 构造Mock对象,根据你实际用到的Globals属性、方法调整配置
const mockGlobals = jasmine.createSpyObj('Globals', 
  ['commonMethod1', 'commonMethod2'], // 数组内填组件用到的Globals方法名
  { commonProp: 'testValue' } // 这里配置组件用到的Globals属性的模拟值
);

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports:[
        FormsModule,
        ReactiveFormsModule,
      ],
      providers:[
        AppService,
        { provide: Globals, useValue: mockGlobals } // 用Mock实例替换真实Globals
      ]
    })
    .compileComponents();
  }));
   beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

修改配置后重新运行测试,组件即可正常初始化,should create用例会顺利通过。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 01:36:05