【问题标题】:Jest change mock after initialize初始化后开玩笑更改模拟
【发布时间】:2021-02-08 03:07:44
【问题描述】:

我想在初始化后更改测试中的模拟数据。 但是当我试图改变它时,它并没有改变......我试图'clearAllMocks()'或使用 jest.spy 但没有任何改变。

  • 当我说改变时,我的意思是“isTablet”数据会改变

影响根项目上许多其他测试的初始化。

jest-modules-mock.js

jest.mock('react-native-device-info', () => ({ isTablet: jest.fn() }));

组件

Welcome.tsx

const deviceType: BgImageByDevice = isTablet() ? 'tablet' : 'mobile';
export default ({ devices }: Welcome): ReactElement => {
const blabla = devices[deviceType]
}

测试

Welcome.test.tsx

const devices = {
    tablet: 'tablet',
    mobile: 'mobile',
  },

describe('<Welcome />', () => {

    test('devices should be mobile', () => {
      jest.doMock('react-native-device-info',() => ({  isTablet: () => false }))
      const Welcome = require('./Welcome').default
      const welcomeShallow = shallow(<Welcome devices={devices} />);
      const imageUrl = welcomeShallow.props().source.uri;
      expect(imageUrl).toBe(devices.mobile);
    });

    test('devices should be tablet', () => {
      jest.doMock('react-native-device-info',() => ({  isTablet: () => true }))
      const Welcome = require('./Welcome').default
      const welcomeShallow = shallow(<Welcome devices={devices} />);
      const imageUrl = welcomeShallow.props().source.uri;
      expect(imageUrl).toBe(devices.tablet);
    });
}

【问题讨论】:

    标签: react-native jestjs ts-jest


    【解决方案1】:

    您可以使用模拟文件更改模拟的值。您可以创建和导出可以在测试中导入并更改实现或返回值的模拟函数。下面是这个过程的一个例子。

    __mocks__\react-native-device-info.js

    export const isTablet = jest.fn();
    

    Welcome.test.js

    import { shallow } from "enzyme";
    import Welcome from "../Welcome";
    import { isTablet } from "../__mocks__/react-native-device-info";
    
    const devices = {
      tablet: 'tablet',
      mobile: 'mobile',
    };
    
    describe('<Welcome />', () => {
      test('devices should be mobile', () => {
        isTablet.mockReturnValue(false);
        const welcomeShallow = shallow(<Welcome devices={devices} />);
        // Your assertions go here
      });
    
      test('devices should be tablet', () => {
        isTablet.mockReturnValue(true);
        const welcomeShallow = shallow(<Welcome devices={devices} />);
        // Your assertions go here
      });
    });
    

    【讨论】:

    • 嗨,谢谢,我仍然收到“背景图片 › 设备应该是平板电脑 expect(received).toBe(expected) // Object.is 相等 预期:“tablet” 收到:“mobile””
    • 您可以在问题中添加更新后的代码吗?我还想看看 source.uri 道具的来源,因为我的代码在上面的例子中应该可以工作,但我认为 Welcome 组件中省略了一些会改变事情的东西。
    猜你喜欢
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 2020-03-05
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多