我在 react 原生中测试我的快照时遇到问题,更具体地说,是我遇到问题的 PixelRatio。
代码胜于 Eloquent - 我简化了代码并消除了所有噪音:
组件:
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建议方案进行Snapshot测试:
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();
});
});
});
最佳答案
当您编写 jest.mock('my-module', () => {...})
时,您告诉 jest
模拟名为'我的模块'
。然后,当您编写 const MyModule = require('my-module')
时,您将得到一个模拟。
因此,如果 PixelRatio
是一个模块,则语句 jest.mock('PixelRatio', () => {...})
是有意义的,但它不是' t。 PixelRatio
是一个全局 JS 变量(准确地说是 JS class
)。您可以如下模拟其静态方法:
1) 使用jest.spyOn
方法:
const mockGet = jest.spyOn(PixelRatio, 'get')
.mockImplementation(() => customImplementation)
const mockRoundToNearestPixel = jest.spyOn(PixelRatio, 'roundToNearestPixel')
.mockImplementation(() => customImplementation)
2) 使用jest.fn
方法:
PixelRatio.get = jest.fn(() => customImplementation)
PixelRatio.roundToNearestPixel = jest.fn(() => customImplementation)
关于reactjs - React Native 如何在 1 个特定测试中模拟 PixelRatio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46092735/