
在 ionic + angular + capacitor 项目中,对 `@capacitor/status-bar` 插件进行单元测试时,因 web 环境下插件未实现而报错,可通过路径别名 + 全局 mock 方式精准模拟 statusbar api,使 `statusbar.setstyle()` 等调用可被 spyon 和断言。
在 Ionic 7 + Angular 16 + Capacitor 5 的技术栈下,直接在测试中 provide: StatusBar, useValue: mockStatusBar 并不能生效——这是因为 @capacitor/status-bar 是一个 ESM 模块,其导出(尤其是默认导出的 StatusBar 对象)在运行时由 TypeScript/ESBuild 解析为静态导入,无法通过 TestBed 的 provider 覆盖。真正的解决路径是:在编译阶段劫持模块解析,用自定义 mock 替换真实模块。
✅ 正确做法:模块级路径重映射 + 静态 mock 实现
1. 配置 tsconfig.spec.json 启用路径别名
在 tsconfig.spec.json 的 compilerOptions 中添加 paths 映射,确保测试构建时所有对 @capacitor/status-bar 的导入都指向你的 mock 文件:
{
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": ["jasmine"],
"paths": {
"@capacitor/status-bar": ["__mocks__/@capacitor/status-bar"]
}
}
}⚠️ 注意:"~@capacitor/status-bar" 是示例中的错误写法(~ 非标准 TS 路径别名),应严格使用 "@capacitor/status-bar" → "__mocks__/@capacitor/status-bar" 映射;同时确保 __mocks__ 目录位于项目根目录(与 src/ 同级)。
2. 创建模块级 Mock 文件
在项目根目录创建文件:__mocks__/@capacitor/status-bar.ts
// __mocks__/@capacitor/status-bar.ts
import {
AnimationOptions,
BackgroundColorOptions,
SetOverlaysWebViewOptions,
StatusBarInfo,
Style,
StyleOptions,
} from '@capacitor/status-bar';
// 导出所有类型和常量(保持类型兼容)
export { Style, StatusBarInfo };
// 模拟全局 StatusBar 对象(必须命名为 StatusBar,且导出为 const)
export const StatusBar = {
getInfo(): Promise {
return Promise.resolve({ visible: true, style: Style.Default });
},
hide(options?: AnimationOptions): Promise {
return Promise.resolve();
},
setBackgroundColor(options: BackgroundColorOptions): Promise {
return Promise.resolve();
},
setOverlaysWebView(options: SetOverlaysWebViewOptions): Promise {
return Promise.resolve();
},
setStyle(options: StyleOptions): Promise {
return Promise.resolve();
},
show(options?: AnimationOptions): Promise {
return Promise.resolve();
},
}; ✅ 关键点:
- 必须导出 const StatusBar = { ... }(非 class 或 function),以匹配原插件导出形式;
- 所有方法返回 Promise.resolve(),避免异步测试阻塞;
- 显式导出 Style 和 StatusBarInfo,确保组件中 import { Style } from '@capacitor/status-bar' 类型不报错。
3. 在测试中直接 spyOn(无需提供 provider)
修改你的 app.component.spec.ts,移除 providers 中对 StatusBar 的手动注入,因为路径重映射已确保所有导入都指向 mock:
// app.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { IonicModule, Platform } from '@ionic/angular';
import { StoreModule, provideMockStore } from '@ngrx/store/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { TranslateModule } from '@ngx-translate/core';
import { StatusBar, Style } from '@capacitor/status-bar'; // ← 此处导入即为 mock 版本
import { AppComponent } from './app.component';
import { SharedModule } from './shared/shared.module';
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture;
let platform: Platform;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AppComponent],
imports: [
BrowserModule,
BrowserAnimationsModule,
CommonModule,
HttpClientTestingModule,
SharedModule.forRoot(),
RouterTestingModule,
IonicModule.forRoot({}),
TranslateModule.forRoot(),
],
providers: [
provideMockStore({ initialState: {} }),
// ✅ 移除:{ provide: StatusBar, useValue: mockStatusBar }
],
schemas: [],
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
platform = TestBed.inject(Platform);
});
it('should call StatusBar.setStyle when on capacitor and theme is light', () => {
// Arrange
spyOn(platform, 'is').and.returnValue(true);
spyOn(StatusBar, 'setStyle'); // ← 直接 spyOn mock 对象
const theme = { theme_style: 'a;b;light' };
// Act
component.loadTheme(theme);
// Assert
expect(StatusBar.setStyle).toHaveBeenCalledTimes(1);
expect(StatusBar.setStyle).toHaveBeenCalledWith({ style: Style.Dark });
});
it('should call StatusBar.setStyle when on capacitor and theme is dark', () => {
spyOn(platform, 'is').and.returnValue(true);
spyOn(StatusBar, 'setStyle');
const theme = { theme_style: 'a;b;dark' };
component.loadTheme(theme);
expect(StatusBar.setStyle).toHaveBeenCalledTimes(1);
expect(StatusBar.setStyle).toHaveBeenCalledWith({ style: Style.Light });
});
}); ? 注意事项与最佳实践
- 不要安装 @capacitor/status-bar 到 devDependencies:该插件仅需在生产环境(Capacitor 原生层)使用;测试中完全由 mock 替代。
- 确保 __mocks__ 不被 ESLint/TSLint 报错:可在 .eslintignore 或 tsconfig.json 中排除该目录。
- Capacitor 5 兼容性:上述 mock 结构兼容 Capacitor 5 的 @capacitor/status-bar@5.x,只需同步更新 StyleOptions 等类型导入路径(仍为 '@capacitor/status-bar')。
- 避免 useClass/useValue 注入 StatusBar:这是常见误区——StatusBar 是模块顶层导出对象,不是可注入的 Angular service,provider 注入无效。
通过该方案,你将彻底规避 "StatusBar plugin is not implemented on web" 错误,并获得 100% 可控、可断言的 StatusBar 行为,真正实现跨平台插件的可靠单元测试。










