当为React Native项目编写单元测试时,我希望能够基于不同平台测试不同的快照。我首先尝试使用
我还尝试将模拟对象包装在
有什么想法可以在同一文件中更改测试的模拟平台吗?
jest.mock
来模拟Platform
,但似乎是异步的。当我有两个单独的文件时,这种方法确实有效,但如果可能的话,我更喜欢将所有内容都放在一个文件中。我尝试了jest.doMock
,因为文档中有以下片段:
然而,我仍然看到不期望的结果。当我在android测试中使用使用babel-jest时,对mock的调用将自动提升到代码块的顶部。如果要明确避免此行为,请使用此方法。 https://facebook.github.io/jest/docs/en/jest-object.html#jestdomockmodulename-factory-options
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();
});
});
有什么想法可以在同一文件中更改测试的模拟平台吗?
jest.requireActual
而不是require.requireActual
。 - David Schumann