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

使用Jest测试React Native库报createChannel非函数错误如何解决

报错原因

两个核心问题导致测试失败:

  • jest.mock 写法错误:当前写法将react-native-push-notification整个模块的默认导出替换为字符串'PushNotification.createChannel',模块上不存在createChannel方法,因此抛出is not a function的类型错误。
  • 测试断言逻辑错误:被测的createChannel函数没有返回值(返回类型为void),将其调用结果赋值给mockFN再断言toHaveBeenCalled,本质是对undefined做函数调用断言,逻辑完全不成立。
修复步骤
  1. 修正模块mock逻辑,模拟出和真实模块结构一致的导出,将createChannel替换为Jest mock函数
  2. 调整断言逻辑,直接引用模块上被mock的createChannel方法做校验,同时建议校验入参保证配置正确,提升测试有效性

修正后的完整测试代码:

import PushNotification from 'react-native-push-notification';
import {createChannel} from '../src/functions/PomodoroFunction';

// 正确mock推送通知模块
jest.mock('react-native-push-notification', () => ({
  __esModule: true, // 标记为ES模块,适配default导入语法
  default: {
    createChannel: jest.fn(), // 将createChannel替换为可监听调用的mock函数
  },
}));

describe('Create Channel unit test', () => {
  // 每个用例执行前清空mock调用记录,避免用例间状态污染
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('Should call PushNotification.createChannel with correct channel config', () => {
    // 执行被测函数
    createChannel();

    // 断言方法被正确调用,且入参符合预期
    expect(PushNotification.createChannel).toHaveBeenCalledTimes(1);
    expect(PushNotification.createChannel).toHaveBeenCalledWith({
      channelId: 'test-channel',
      channelName: 'Test Channel',
      vibrate: true,
    });
  });
});
补充说明
  • 配置__esModule: true是为了适配ES Module的import xxx from 'xxx'默认导入语法,避免导入结构错位
  • 仅断言方法被调用的测试覆盖度不足,补充入参校验可以保证通知渠道的配置不会被误改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 13:00:53