如何使用 Jest 模拟 React-Native Platform.OS?

问题描述 投票:0回答:2

Jest runner 使用“ios”作为默认操作系统(Plaform.OS)进行反应本机测试。 如何在具有平台相关代码的笑话中进行测试。更进一步,如何模拟模块中导入的静态常量。

代码如下: utils.ts:

import { Platform } from "react-native";
export const isIOS = Platform.OS === "ios"; // note constant, not function

items.ts:

import { isIOS } from "@my/utils";
export const items = [{
    id: 1,
    name: isIOS ? "Apple" : "Android"
}]

测试:

import { items } from "./items";

// not working because Platform.OS is used statically during import statement
it("should be android", () => {
  Platform.OS = "android"; // too late...
  expect(items[0].name).toBe("Android"); // fail: Apple
}

it("should be ios", () => {
  Platform.OS = "ios";
  expect(items[0].name).toBe("Apple"); // works due to default platform value in Jest
}

我在 test/it 块中使用

jest.resetModules()
require
看到了一些解决方法(并在 require 之前更改 Plaform.OS),但确实存在更简单的方法来实现这一目标?

react-native jestjs mocking
2个回答
2
投票

在你的测试文件中

import { Platform } from 'react-native'

jest.doMock('react-native/Libraries/Utilities/Platform.android.js', () => ({
  OS: 'android',
  select: jest.fn(),
}))

jest.doMock('react-native/Libraries/Utilities/Platform.ios.js', () => ({
  OS: 'android',
  select: jest.fn(),
}))

describe('Platform', () => {
  it('Should be android', () => {
    expect(Platform.OS).toEqual('android')
  })

  it('Should be ios', () => {
    Platform.OS = 'ios'
    expect(Platform.OS).toEqual('ios')
  })

  it('Should be android', () => {
    Platform.OS = 'android'
    expect(Platform.OS).toEqual('android')
  })
})


0
投票

只需将 iOS 实现替换为 Android 实现即可。对于 Android,请使用相反的方式。

    jest.mock('react-native/Libraries/Utilities/Platform.ios.js', () => ({
      ...jest.requireActual(
        'react-native/Libraries/Utilities/Platform.android.js',
      ),
    }));
© www.soinside.com 2019 - 2024. All rights reserved.