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

Ionic5升级Capacitor3后验证SplashScreen.hide()的Jasmine测试失败

问题根因

你在组件中没有使用Angular依赖注入的SplashScreen实例,而是直接引用了从@capacitor/splash-screen导入的静态全局对象:

  • 你在app.component.ts中写了private splashScreen = SplashScreen;,这个SplashScreen是导入的原始对象,和测试模块里提供的mock没有任何关系
  • 测试里提供的{ provide: SplashScreen, useValue: splashScreenSpy }完全没有被组件用到,所以你调用的hide方法根本不是你创建的spy对象,断言自然失败。

解决方案

有两种可选方案,按需选择即可:

方案一:修改组件,使用依赖注入(更符合Angular最佳实践)

修改app.component.ts代码:

  1. 删掉类属性行private splashScreen = SplashScreen;
  2. 在构造函数参数中注入SplashScreen:
constructor(
  private platform: Platform, 
  private translate: TranslateService,
  private settingsService: SettingsService, 
  private authService: AuthenticationService,
  // 新增注入SplashScreen
  private splashScreen: SplashScreen
) {
  this.initializeApp();
  this.authService.logIn();
}

原有其他代码不需要改动,测试代码也不需要改动,运行测试即可通过。

方案二:不修改组件代码,直接mock全局导入的SplashScreen对象

修改app.component.spec.ts代码:

  1. 导入整个SplashScreen模块:
import * as SplashScreenModule from '@capacitor/splash-screen';
  1. 在beforeEach中直接spy静态方法,删掉原有providers中的SplashScreen提供项:
beforeEach(waitForAsync(() => {
  // 直接mock静态的hide方法
  spyOn(SplashScreenModule.SplashScreen, 'hide').and.resolveTo();
  platformReadySpy = Promise.resolve();
  platformSpy = jasmine.createSpyObj('Platform', { 
    ready: platformReadySpy, 
    is: (type: string) => type === 'hybrid'
  });

  TestBed.configureTestingModule({
    declarations: [AppComponent],
    imports: [TranslateModule.forRoot()],
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
    providers: [
      { provide: Platform, useValue: platformSpy }
      // 删掉原来的SplashScreen提供项
    ]
  }).compileComponents();
}));
  1. 修改断言,判断静态方法是否被调用:
expect(SplashScreenModule.SplashScreen.hide).toHaveBeenCalled();

两种方案都可以解决你的断言失败问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:36:02