Enzyme Mock ToastAndroid React Native Component

Viewed 645

I am testing a react native component that uses ToastAndroid Component in a method, and while testing with enzyme I keep getting error TypeError: _reactNative.ToastAndroid.show is not a function

I am using react-native-mock-renderer for jest mock and my component has a method that gets called in with an onPress handler.

 validateAndProceed = () => {
    ToastAndroid.show(
        'Show toast',
        ToastAndroid.SHORT,
      );
  };

and my test to verify

it('should validate and process', () => {
    const wrapper = shallow(<Component
    />);
    const instance = wrapper.dive().instance();
    jest.spyOn(instance, 'validateAndProceed');
    instance.validateAndProceed();
    expect(instance.validateAndProceed).toHaveBeenCalled();
  });

I created a custom mock for the ToastAndroid

const ToastAndroid = {
  SHORT: '',
  LONG: '',

  TOP: '',
  BOTTOM: '',
  CENTER: '',

  show: jest.fn(),
  showWithGravity: jest.fn(),
  showWithGravityAndOffset: jest.fn(),
};

module.exports = ToastAndroid;

Still a not working

1 Answers

You don't need to mock the entire module. Mocking only relevant functions and constants did it for me.

Example:

ToastAndroid.showWithGravity = jest.fn();
ToastAndroid.show = jest.fn(); 
Related