【发布时间】:2017-09-07 09:27:22
【问题描述】:
我无法在 react-native 中测试我的快照,更具体地说,是我遇到问题的 PixelRatio。
代码胜于雄辩——我已经简化了代码并消除了所有干扰:
组件:
const Slide = (props) => (
<Image
source={props.source}
style={PixelRatio.get() === 2 ?
{ backgroundColor: 'red' } :
{ backgroundCoor: 'green' }}
/>
);
快照测试:
import { Platform } from 'react-native';
describe('When loading the Slide component', () => {
it('should render correctly on ios', () => {
Platform.OS = 'ios';
const tree = renderer.create(
<Provider store={store}>
<Slide />
</Provider>,
).toJSON();
expect(tree).toMatchSnapshot();
});
describe('on devices with a pixelRatio of 2', () => {
it('it should render correctly', () => {
jest.mock('PixelRatio', () => ({
get: () => 2,
roundToNearestPixel: jest.fn(),
}));
const tree = renderer.create(
<Provider store={store}>
<Slide />
</Provider>,
).toJSON();
expect(tree).toMatchSnapshot();
});
});
});
但这不起作用,经过一番挖掘,我发现了一个已经解决的bug on github - 显然你需要使用beforeEach。但这似乎也不起作用或者我做错了?
使用github建议解决方案的快照测试:
import { Platform } from 'react-native';
describe('When loading the Slide component', () => {
it('should render correctly on ios', () => {
Platform.OS = 'ios';
const tree = renderer.create(
<Provider store={store}>
<Slide />
</Provider>,
).toJSON();
expect(tree).toMatchSnapshot();
});
describe('on devices with a pixelRatio of 2', () => {
it('it should render correctly', () => {
beforeEach(() => {
jest.mock(pxlr, () => ({
get: () => 2,
roundToNearestPixel: jest.fn(),
}));
const pxlr = require('react-native').PixelRatio;
}
const tree = renderer.create(
<Provider store={store}>
<Slide />
</Provider>,
).toJSON();
expect(tree).toMatchSnapshot();
});
});
});
【问题讨论】:
标签: reactjs unit-testing react-native jestjs