在为React Native项目编写单元测试时,我希望能够根据不同的平台测试不同的快照。
我首先尝试jest.mock
来模拟Platform
,但似乎是异步的。当我有两个单独的文件时,这种方法确实有效,但我希望尽可能将所有内容保存在一个文件中。
我试过jest.doMock
因为文档中的这个片段:
使用babel-jest时,对mock的调用将自动提升到代码块的顶部。如果要明确避免此行为,请使用此方法。 https://facebook.github.io/jest/docs/en/jest-object.html#jestdomockmodulename-factory-options
然而,我仍然看到不良后果。当我在Android测试中console.log
时,我发现Platform.OS
是我设置的第一个doMock
。
我还尝试将模拟包装在beforeEach
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();
});
});
关于如何在同一文件中更改模拟平台以进行测试的任何想法?
答案 0 :(得分:1)
关于如何在another question中解决这个问题,有很多建议,但是根据你们的相同要求(在中测试不同的操作系统 suite文件,并在一个测试运行中)。
我最终使用了一个有点笨重的琐碎辅助函数来解决这个问题,可以在测试中按照预期进行模拟 - 类似于:
export function getOS() {
return Platform.OS;
}
在代码中使用它代替Platform.OS
,然后在测试中简单地模拟它,例如
it('does something on Android', () => {
helpers.getOS = jest.fn().mockImplementationOnce(() => 'android');
// ...
}
这就是诀窍;该想法归功于this guy。