Reputation: 734
I want to change mock data inside tests after I initialize it. But when I'm trying to change it, it didn't change... I tried to 'clearAllMocks()' or use jest.spy but nothing changed it.
The initialize that impacts a lot of other tests on the root project.
jest-modules-mock.js
jest.mock('react-native-device-info', () => ({ isTablet: jest.fn() }));
The component
Welcome.tsx
const deviceType: BgImageByDevice = isTablet() ? 'tablet' : 'mobile';
export default ({ devices }: Welcome): ReactElement => {
const blabla = devices[deviceType]
}
The tests
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);
});
}
Upvotes: 0
Views: 864
Reputation: 1887
You can change the value of a mock using a mock file. You can create and export a mock function that you can import in your test and change the implementation or return value. Below is an example of this process.
__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
});
});
Upvotes: 1