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

如何在Cypress组件测试中实现依赖注入(DI)?

Cypress测试Angular带DI依赖的组件解决方案

当测试依赖注入(如LoggingService)的Angular组件时,Cypress挂载组件会因找不到服务提供者报错,示例组件及报错信息如下:

示例组件代码

@Component({
  selector: 'app-not-authorized',
  templateUrl: './not-authorized.component.html',
  styleUrls: ['./not-authorized.component.scss']
})
export class NotAuthorizedComponent implements OnInit  {
  constructor(private logger: LoggingService) { }

  ngOnInit() {
    this.logAccess();
  }
...
}

报错信息

1) NotAuthorizedComponent
       mount:
     NullInjectorError: R3InjectorError(DynamicTestModule)[LoggingService -> LoggingService]:
  NullInjectorError: No provider for LoggingService!
      at NullInjector.get (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:13946:27)
      at R3Injector.get (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:14113:33)
      at R3Injector.get (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:14113:33)
      at NgModuleRef.get (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:24641:33)
      at Object.get (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:24318:35)
      at lookupTokenUsingModuleInjector (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:6183:39)
      at getOrCreateInjectable (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:6295:12)
      at ɵɵdirectiveInject (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:17219:12)
      at NodeInjectorFactory.NotAuthorizedComponent_Factory [as factory] (ng:///NotAuthorizedComponent/ɵfac.js:4:50)
      at getNodeInjectable (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:6390:44)

解决方法

1. 注入模拟(Mock)服务

组件测试优先推荐使用模拟服务,避免真实服务的副作用,同时便于验证组件交互逻辑:

// 定义LoggingService的模拟类
class MockLoggingService {
  logAccess() {
    // 模拟业务逻辑,可添加自定义断言点
    cy.log('模拟日志服务记录未授权访问');
  }
}

describe('NotAuthorizedComponent', () => {
  it('成功挂载组件并验证日志调用', () => {
    cy.mount(NotAuthorizedComponent, {
      providers: [
        { provide: LoggingService, useClass: MockLoggingService }
      ]
    });
    // 此处添加组件行为断言
  });
});

2. 导入服务所属模块

若必须使用真实服务,可直接导入该服务所在的模块(模块需已配置服务提供者):

import { LoggingModule } from '../path/to/logging.module';

describe('NotAuthorizedComponent', () => {
  it('挂载组件并使用真实日志服务', () => {
    cy.mount(NotAuthorizedComponent, {
      imports: [LoggingModule]
    });
    // 后续测试逻辑
  });
});

3. 直接提供真实服务

如果服务未封装在模块中,可直接在测试的providers数组中声明:

describe('NotAuthorizedComponent', () => {
  it('挂载组件并注入真实日志服务', () => {
    cy.mount(NotAuthorizedComponent, {
      providers: [LoggingService]
    });
    // 后续测试逻辑
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:25:27