如何用Jest来模仿React原生平台?

xvw2m8pv  于 2022-11-17  发布在  React
关注(0)|答案(1)|浏览(114)

Jest runner使用“ios”作为默认操作系统(平台操作系统)来进行React原生测试。如何在Jest中进行具有平台相关代码的测试。此外,如何模拟模块中导入的静态常量。
代码如下: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的变通方法(并在需要之前更改平台操作系统),但是否存在更简单的方法来实现这一点?

wgeznvg7

wgeznvg71#

在 测试 文件 中

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')
  })
})

中 的 每 一 个

相关问题