React Native:Jest 模拟平台

Tur*_*ets 3 unit-testing snapshot jestjs react-native babel-jest

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

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

我尝试了jest.doMock因为文档中的这段代码:

使用 babel-jest 时,对模拟的调用将自动提升到代码块的顶部。如果您想明确避免此行为,请使用此方法。 https://facebook.github.io/jest/docs/en/jest-object.html#jestdomockmodulename-factory-options

但是我仍然看到不希望的结果。当我console.log在 android 测试中时,我发现这Platform.OS就是我设置的第一个值doMock

我还尝试将模拟包装在 abeforeEach中,describe因为我认为这可能有助于确定范围 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();
  });
});
Run Code Online (Sandbox Code Playgroud)

关于如何更改同一文件中的测试的模拟平台有什么想法吗?

d0g*_*3r7 5

\n\n

在另一个问题中有很多关于如何解决这个问题的建议,但考虑到您有相同的要求(在同一套件文件和一次测试运行中测试不同操作系统),这些建议都不适合我。

\n\n

我最终用一个有点笨重的琐碎辅助函数解决了这个问题,该函数可以在测试 \xe2\x80\x93 中按预期进行模拟,例如:

\n\n
export function getOS() {\n  return Platform.OS;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
it(\'does something on Android\', () => {\n  helpers.getOS = jest.fn().mockImplementationOnce(() => \'android\');\n  // ...\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这就成功了;这个想法的功劳归功于这个家伙

\n