初始化测试后,我希望在测试中更改模拟数据。但当我试图改变它时,它并没有改变.我试图使用“clearAllMocks()”或使用jest.spy,但是没有任何改变。
初始化会影响根项目上的许多其他测试。
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);
});
}发布于 2021-02-07 19:07:44
可以使用模拟文件更改模拟的值。您可以创建和导出一个模拟函数,您可以在测试中导入该函数,并更改实现或返回值。下面是这个过程的一个例子。
__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
});
});https://stackoverflow.com/questions/66090282
复制相似问题