React Native 如何在 1 个特定测试中模拟 PixelRatio

mXX*_*mXX 2 unit-testing reactjs jestjs react-native

我在反应原生中测试我的快照时遇到问题,更具体地说,是我遇到问题的 PixelRatio。

代码胜于雄辩——我简化了代码并消除了所有噪音:

组件:

const Slide = (props) => (
  <Image
    source={props.source}
        style={PixelRatio.get() === 2 ?
            { backgroundColor: 'red' } :
            { backgroundCoor: 'green' }}
  />
);
Run Code Online (Sandbox Code Playgroud)

快照测试

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();
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

但这不起作用,经过一番挖掘,我在 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();
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

GPr*_*ost 5

当你编写时jest.mock('my-module', () => {...}),你告诉jestmock模块的名称为'my-module'. 然后当你写作时,const MyModule = require('my-module')你会得到一个模拟。

因此,如果它是一个模块,那么语句jest.mock('PixelRatio', () => {...})就有意义PixelRatio,但事实并非如此。PixelRatio是一个全局 JS 变量(class准确地说是 JS)。您可以如下模拟其静态方法:

1)使用jest.spyOn方法:

const mockGet = jest.spyOn(PixelRatio, 'get')
  .mockImplementation(() => customImplementation)
const mockRoundToNearestPixel = jest.spyOn(PixelRatio, 'roundToNearestPixel')
  .mockImplementation(() => customImplementation)
Run Code Online (Sandbox Code Playgroud)

2)使用jest.fn方法:

PixelRatio.get = jest.fn(() => customImplementation)
PixelRatio.roundToNearestPixel = jest.fn(() => customImplementation)
Run Code Online (Sandbox Code Playgroud)