在为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
。
我还尝试将模拟程序包装在中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();
});
});
关于如何在同一文件中更改模拟平台以进行测试的任何想法?
关于如何解决另一个问题,有很多建议,但是鉴于您有相同的要求(在同一套件文件中并在一个测试运行中针对不同的OS进行测试),它们中的任何一个都不对我有用。
最终,我使用了一个笨拙的琐碎的辅助函数来解决该问题,该函数可以在测试中按预期进行模拟,例如:
export function getOS() {
return Platform.OS;
}
用它代替Platform.OS
代码,然后在测试中简单地模拟它,例如
it('does something on Android', () => {
helpers.getOS = jest.fn().mockImplementationOnce(() => 'android');
// ...
}
那成功了;这个想法归功于这个家伙。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句