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

如何在Jest单元测试中mock @ionic/core的isPlatform方法返回true

React Ionic项目Jest单元测试mock isPlatform方法教程

原业务实现

开发React Ionic应用时,判断应用是否运行在iOS设备上的实现代码如下:

import { isPlatform } from "@ionic/core";

const isIOS = isPlatform("ios");

失效的mock写法

最初尝试直接在jest.mock的工厂函数中返回指定方法,调用isPlatform时仍然返回false,无效代码如下:

jest.mock("@ionic/core", () => ({
    isPlatform: () => { 
        return true;
    }
}));

生效的正确方案

需要先完整mock整个@ionic/core模块,再导入模块后重写isPlatform方法即可生效,代码如下:

jest.mock("@ionic/core");
import * as Ionic from '@ionic/core';

(Ionic as any).isPlatform = jest.fn(() => true);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:45:03