React Native:Jest 模拟平台

React Native: Jest mocking Platform

在为 React Native 项目编写单元测试时,我希望能够测试基于不同平台的不同快照。

我首先尝试 jest.mock 模拟 Platform 但似乎是异步的。当我有两个单独的文件时,这种方法确实有效,但如果可能,我更愿意将所有内容保存在一个文件中。

我尝试 jest.doMock 因为文档中的这个片段:

When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior. https://facebook.github.io/jest/docs/en/jest-object.html#jestdomockmodulename-factory-options

但是我仍然看到了不良结果。当我在 android 测试中 console.log 时,我看到 Platform.OS 是我将第一个 doMock 设置为的值。

我还尝试将模拟包装在 beforeEachdescribe 因为我认为这可能有助于确定范围 http://facebook.github.io/jest/docs/en/setup-teardown.html#scoping

 describe('ios test', () => {
  it('renders ui correctly', () => {
    jest.doMock('Platform', () => {
      const Platform = require.requireActual('Platform');
      Platform.OS = 'ios';
      return Platform;
    });
    const wrapper = shallow(<SomeComponent />);
    const tree = renderer.create(wrapper).toJSON();
    expect(tree).toMatchSnapshot();
  });
});

describe('android test', () => {
  it('renders ui correctly', () => {
    jest.doMock('Platform', () => {
      const Platform = require.requireActual('Platform');
      Platform.OS = 'android';
      return Platform;
    });
    const wrapper = shallow(<SomeComponent />);
    const tree = renderer.create(wrapper).toJSON();
    expect(tree).toMatchSnapshot();
  });
});

关于如何在同一文件中更改模拟平台以进行测试的任何想法?

中有很多关于如何解决这个问题的建议,但其中 none 也对我有用,因为你有相同的要求(针对不同操作系统的测试相同 套件文件并在 one 测试 运行).

我最终用一个有点笨拙的辅助函数解决了这个问题,可以在测试中像预期的那样被模拟——比如:

export function getOS() {
  return Platform.OS;
}

在您的代码中使用它而不是 Platform.OS,然后在您的测试中简单地模拟它,例如

it('does something on Android', () => {
  helpers.getOS = jest.fn().mockImplementationOnce(() => 'android');
  // ...
}

成功了;这个想法的功劳归功于 this guy.