首页 > 解决方案 > 开玩笑测试没有正确重置模拟值

问题描述

我正在尝试测试组件的样式道具,该道具会根据名为isIphoneX. 正因为如此,我编写了 2 个测试用例,在其中我以不同的方式模拟了该函数的返回值。因此,我希望组件每次都有不同的样式道具。

第一个测试通过(因为 isIphoneX 被评估为假),但第二个测试不断返回 80,而不是高度的 110。

请注意,我已经尝试使用:

jest.clearAllMocks()、jest.resetAllMocks()、jest.resetModules()、beforeEach/afterEach 的外部、内部和内部。

我相信这个问题与可以模拟 isIphoneX 之前运行的组件 CameraOverlay 有关。

// CameraOverlay.js

import { isIphoneX } from 'utils/device';

const styles = StyleSheet.create({
  capturePanel: {
    height: isIphoneX() ? 110 : 80,
  },
});

const CameraOverlay = () => (
  <View style={styles.capturePanel} testID="capturePanel">
    Some dummy text
  </View>
);

export default CameraOverlay;
// CameraOverlay.test.js
import { shallow } from 'enzyme';
import CameraOverlay from 'components/CameraOverlay';
import { isIphoneX } from 'utils/device';

jest.mock('utils/device');


describe('<View style={styles.capturePanel} testID="capturePanel">', () => {
    let wrapper;
    beforeEach(() => {
      wrapper = shallow(<CameraOverlay {...defaultProps} />);
    });
    it('renders correct style height for standard devices', () => {
      isIphoneX.mockReturnValue(false);
      expect(
        wrapper.find({ testID: 'capturePanel' }).prop('style').height,
      ).toEqual(80);
    });
    it('renders correct style height for iPhone X (and newer) devices', () => {
      isIphoneX.mockReturnValue(true);
      expect(
        wrapper.find({ testID: 'capturePanel' }).prop('style').height,
      ).toEqual(110);
    });
  });

标签: javascriptreactjsunit-testingreact-native

解决方案


推荐阅读