在为 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
设置为的内容。
我还尝试将模拟包装在 describe
中的 beforeEach
中,因为我认为这可能有助于确定范围
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();
});
});
关于如何在同一个文件中更改模拟平台以进行测试有什么想法吗?
最佳答案
在another question中有很多关于如何解决这个问题的建议。 ,但它们都不适合我,因为您有相同的要求(在相同套件文件和一个测试运行中测试不同的操作系统)。
我最终用一个有点笨拙的辅助函数解决了这个问题,该辅助函数可以在测试中按预期进行模拟——类似于:
export function getOS() {
return Platform.OS;
}
在您的代码中使用它代替 Platform.OS
,然后在您的测试中简单地模拟它,例如
it('does something on Android', () => {
helpers.getOS = jest.fn().mockImplementationOnce(() => 'android');
// ...
}
成功了;这个想法的功劳归功于this guy .
关于unit-testing - react native : Jest mocking Platform,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47537477/