首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在初始化后开玩笑更改模拟

在初始化后开玩笑更改模拟
EN

Stack Overflow用户
提问于 2021-02-07 16:32:45
回答 1查看 483关注 0票数 0

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

  • 当我说改变时,我的意思是‘isTablet’数据将改变

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

代码语言:javascript
复制
jest-modules-mock.js

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

组件

代码语言:javascript
复制
Welcome.tsx

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

试验

代码语言:javascript
复制
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);
    });
}
EN

回答 1

Stack Overflow用户

发布于 2021-02-07 19:07:44

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

__mocks__\react-native-device-info.js

代码语言:javascript
复制
export const isTablet = jest.fn();

Welcome.test.js

代码语言:javascript
复制
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
  });
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66090282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档