CodeLover
CodeLover

Reputation: 208

Testing a button click in React Native with Jest and enzyme

I am new to testing react native apps with Jest and have no idea what i am doing. I have done some research online but most of the courses seem to be outdated.

I have an image within my app that when pressed takes the user to another screen. After doing some research it seems that using enzyme is the way to do this (this is most likely outdated and I am doing it wrong).

Here is my code.

import 'react-native';
import React from 'react';
import HomeScreen, { TouchableOpacity } from '../app/HomeScreen';
import { render, fireEvent } from 'react-native-testing-library';
import { configure, shallow, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() })

it("can press the button", () => {
  
const onPressMock = jest.fn();

const button = shallow((<TouchableOpacity onPress={onPressMock} />));
button.find('button').simulate('click');
expect(onPressMock).toHaveBeenCalled();
expect(onPressMock.mock.calls.length).toEqual(1);
});

When I run my test with yarn I get the following error, is there any way to fix this?

error

Here is the code my HomeScreen

export default class HomeScreen extends React.Component 
{
 render() {
   
  return (
  <ScrollView>
     <View style={{flex:1}}>
     <TouchableOpacity onPress={() => this.props.navigation.navigate('Listen')}>
     <ImageBackground source={require('./bible.png')} style={{width: '100%', opacity: 0.8}}>
              <Text style={styles.MainText}>Sermons</Text>
              </ImageBackground>
         </TouchableOpacity>
         <TouchableOpacity onPress={() => this.props.navigation.navigate('Events')}>
      <ImageBackground source={require('./events.png')} style={{width: '100%', opacity: 0.8}}>
              <Text style={styles.MainText}>Events</Text>
         </ImageBackground>
         </TouchableOpacity>
         <TouchableOpacity onPress={() => this.props.navigation.navigate('Connect')}>
         <ImageBackground source={require('./connect.png')} style={{width: '100%', opacity: 0.8}}>
              <Text style={styles.MainText}>Connect</Text>
         </ImageBackground>
         </TouchableOpacity>
         <TouchableOpacity onPress={() => this.props.navigation.navigate('About')}>
      <ImageBackground source={require('./church.png')} style={{width: '100%', opacity: 0.8}}>
              <Text style={styles.MainText}>About</Text>
         </ImageBackground>
         </TouchableOpacity>
     </View>

    </ScrollView>
  )
 }
}

Upvotes: 0

Views: 3958

Answers (1)

You should import TouchableOpacity from 'react-native' in your test, then, try using "mount" (from the 'enzyme' package as well) instead of "shallow" to create your constant "button", that should do it.

Upvotes: 1

Related Questions