初始化后更改mock



我想在初始化后更改测试中的模拟数据。但当我试图改变它时,它却没有改变……我尝试"clearAllMocks()"或使用jest。间谍,但没有改变它。

  • 当我说改变时,我的意思是' 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);
});
}

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

__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
});
});

最新更新