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

如何为Ionic Capacitor推送通知方法编写测试用例?

测试Ionic Capacitor推送通知权限请求与注册逻辑

要测试这类依赖原生Capacitor API的代码,核心是模拟PushNotifications模块的行为,避免依赖真机环境。下面用Jasmine(Angular默认测试框架)或Vitest为例,分场景编写测试用例:

1. 准备工作:模拟PushNotifications模块

首先在测试文件中,手动模拟Capacitor的PushNotifications类,替换真实实现:

import { PushNotifications } from '@capacitor/push-notifications';

// 模拟整个PushNotifications模块
jest.mock('@capacitor/push-notifications', () => ({
  PushNotifications: {
    requestPermissions: jest.fn(),
    register: jest.fn(),
    addListener: jest.fn((eventName, callback) => ({
      // 保留触发回调的能力,方便测试监听器
      callback
    }))
  }
}));

2. 测试权限授予场景

验证当用户授予权限时,register方法被正确调用:

it('should call register when permissions are granted', async () => {
  // 模拟requestPermissions返回授予状态
  (PushNotifications.requestPermissions as jest.Mock).mockResolvedValue({ receive: 'granted' });
  
  // 执行你的权限请求代码(假设这段代码在某个服务或组件的init方法里)
  await yourComponentOrService.initPushNotifications();
  
  // 验证register被调用
  expect(PushNotifications.register).toHaveBeenCalled();
});

3. 测试权限拒绝场景

验证当用户拒绝权限时,register不会被调用,且错误逻辑执行(如果有):

it('should NOT call register when permissions are denied', async () => {
  (PushNotifications.requestPermissions as jest.Mock).mockResolvedValue({ receive: 'denied' });
  
  // 假设你有个记录权限状态的变量或方法
  await yourComponentOrService.initPushNotifications();
  
  expect(PushNotifications.register).not.toHaveBeenCalled();
  // 如果有错误提示逻辑,比如设置errorMessage,验证它是否被赋值
  expect(yourComponentOrService.errorMessage).toBe('推送权限被拒绝');
});

4. 测试registration监听器

验证注册成功时,监听器能正确处理token:

it('should trigger alert on successful registration', () => {
  let registrationCallback: (token: { value: string }) => void;
  
  // 捕获addListener传入的回调函数
  (PushNotifications.addListener as jest.Mock).mockImplementation((event, callback) => {
    if (event === 'registration') {
      registrationCallback = callback;
    }
    return { remove: jest.fn() };
  });
  
  // 初始化推送逻辑,让addListener执行
  yourComponentOrService.initPushNotifications();
  
  // 模拟触发registration事件,传入测试用token
  const testToken = { value: 'test-fcm-token-123' };
  registrationCallback(testToken);
  
  // 验证alert被调用(需要先模拟alert)
  window.alert = jest.fn();
  expect(window.alert).toHaveBeenCalledWith(`Push registration success, token: ${testToken.value}`);
});

关键注意事项

  • 所有原生Capacitor API都需要模拟,不要在测试环境依赖真实的原生实现。
  • 如果用Angular,可借助TestBed提供模拟服务,或者直接mock模块。
  • 测试异步逻辑时,要确保使用async/await或fakeAsync处理Promise,避免测试提前结束。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:15:16