Using Jest and Testing Library with React Native Part IV: Testing a Button

Justin Leach React, React Native, Testing, Testing React Native Series, Tutorial Leave a Comment

This is part IV of my blog series on testing React Native with Jest and Testing Library. In this part, we’ll talk about Button Testing in React Native. If you haven’t already, take a look at the previous installments!

Seriers Outline:

  • Part I: Setting Up
  • Part II: Writing the First Test
  • Part III: Testing for an Element That Isn’t Present
  • Part IV: Button Testing – Current Article
  • Part V: Testing Styles of a Component
  • Part VI: Functional Testing
  • Part VII: Further Helpful Information
  • In our last tutorial, we went over how to test for an element/component that is not found. In this tutorial, we will go over adding a button to our React Native codebase. After the button is added, we’ll test it.

    Adding a Button

    In React Native, you’ll notice that you have a few options for a button component. There is Button, TouchableOpacity, Pressable, and others. For this tutorial, we will be using Button.

    First things first, navigate to App.js in your root directory. We will be adding the following code.

    import {Button, StyleSheet, Text, View} from 'react-native';
    
    <Button
      title="Press me!"
      onPress={() => {}}
      testID="pressMeButton"
      accessibilityLabel="Press me"
    />
    

    Right now, we are adding onPress and accessibilityLabel. We will go over what they are and what they do a little later on in this blog.

    App.js should now look like this:

    import React from 'react';
    import {Button, StyleSheet, Text, View} from 'react-native';
    
    const App = () => {
      return (
        <View style={styles.body>
          <View style={styles.sectionContainer}>
           <Text style={styles.sectionTitle}>Hello World!</Text>
          </View>
    
          <Button
            title="Press me!"
            onPress={() => {}}
            testID="pressMeButton"
            accessibilityLabel="Press me"
          />
        /View>
      );
    };
    
    const styles = StyleSheet.create({
      body: {
        backgroundColor: '#ffffff',
      },
      sectionContainer: {
        marginTop: 32,
        paddingHorizontal: 24,
      },
      sectionTitle: {
        fontSize: 24,
        fontWeight: '600',
        color: '#000000',
      },
    });
    
    export default App;
    

    Testing a Button

    For our first Button test, we will be using testID. TestId is a property we can search for within our test.

    Now, let’s add a new test to App.test.js.

    it('should find the button via testId', () => {
        const testIdName = 'pressMeButton';
    
        const {getByTestId} = render(<App />);
    
        const foundButton = getByTestId(testIdName);
    
        expect(foundButton).toBeTruthy();
    });
    

    App.test.js should now look like this:

    import React from 'react';
    import {cleanup, render} from '@testing-library/react-native';
    
    import App from '../App';
    
    afterEach(cleanup);
    
    describe('App', () => {
      it('should show hello world', () => {
        const helloWorldText = 'Hello World!';
        const notFoundText = 'Not found text';
    
        const {toJSON, getByText, queryByText} = render(<App />);
    
        const foundHelloWorldTextElement = getByText(helloWorldText);
        const notFoundTextElement = queryByText(notFoundText);
    
        expect(foundHelloWorldTextElement.props.children).toEqual(helloWorldText);
        expect(notFoundTextElement).toBeNull();
        expect(toJSON()).toMatchSnapshot();
      });
    
      it('should find the button via testId', () => {
        const testIdName = 'pressMeButton';
    
        const {getByTestId} = render(<App />);
    
        const foundButton = getByTestId(testIdName);
    
        expect(foundButton).toBeTruthy();
      });
    });
    

    Once you have the code entered, run the test!

    Uh-oh, we got an error: 1 snapshot failed from 1 test suite. Looks like our first test is failing: ✕ should show hello world (220 ms).

    Wait! Don’t freak out! This happens when you update the UI and the snapshot is not aware of it. There is an easy fix for it. If using yarn, run yarn test -u. If using npm, run npm test -u. This will update the snapshot and fix the test.

    Within the error of 1 snapshot failed from 1 test suite, you should see Inspect your code changes or run yarn test -u (if using yarn) to update them. This is Jest trying to help give clues on how to fix the issue.

    You should now see:

    Alright, we’ve begun testing our button, but now, let’s dive even deeper into testing.

    Testing a Button Using accessibilityLabel

    For our second Button test, we will be using accessibilityLabelaccessibilityLabel can be used to make sure your sites and apps are accessible and navigatable for the blind.

    Let’s add a new test to App.test.js.

    it('should find the button via accessibilityLabel', () => {
      const accessibilityLabel = 'Press me';
      
      const {getByA11yLabel} = render(<App />);
    
      const foundButton = getByA11yLabel(accessibilityLabel);
    
      expect(foundButton).toBeTruthy();
    });
    

    App.test.js should look like this:

    import React from 'react';
    import {cleanup, render} from '@testing-library/react-native';
    
    import App from '../App';
    
    afterEach(cleanup);
    
    describe('App', () => {
      it('should show hello world', () => {
        const helloWorldText = 'Hello World!';
        const notFoundText = 'Not found text';
    
        const {toJSON, getByText, queryByText} = render(<App />);
    
        const foundHelloWorldTextElement = getByText(helloWorldText);
        const notFoundTextElement = queryByText(notFoundText);
    
        expect(foundHelloWorldTextElement.props.children).toEqual(helloWorldText);
        expect(notFoundTextElement).toBeNull();
        expect(toJSON()).toMatchSnapshot();
      });
    
      it('should find the button via testId', () => {
        const testIdName = 'pressMeButton';
    
        const {getByTestId} = render(<App />);
    
        const foundButton = getByTestId(testIdName);
    
        expect(foundButton).toBeTruthy();
      });
    
      it('should find the button via accessibilityLabel', () => {
        const accessibilityLabel = 'Press me';
    
        const {getByA11yLabel} = render(<App />);
    
        const foundButton = getByA11yLabel(accessibilityLabel);
    
        expect(foundButton).toBeTruthy();
      });
    });
    

    Now, all we have to do is run the tests!

    You should see something like this:

    Additionally, you have options for test API’s! Here are a few different choices you could use.

    Testing the Title in the Button

    Let’s add a new test to App.test.js:

    it('should find the button title', () => {
      const title = 'Press me!';
      
      const {getByText} = render(<App />);
    
      const foundButtonTitle = getByText(title);
    
      expect(foundButtonTitle.props.children).toEqual(title);
    });
    

    Now, App.test.js should look like this:

    import React from 'react';
    import {cleanup, render} from '@testing-library/react-native';
    
    import App from '../App';
    
    afterEach(cleanup);
    
    describe('App', () => {
      it('should show hello world', () => {
        const helloWorldText = 'Hello World!';
        const notFoundText = 'Not found text';
    
        const {toJSON, getByText, queryByText} = render(<App />);
    
        const foundHelloWorldTextElement = getByText(helloWorldText);
        const notFoundTextElement = queryByText(notFoundText);
    
        expect(foundHelloWorldTextElement.props.children).toEqual(helloWorldText);
        expect(notFoundTextElement).toBeNull();
        expect(toJSON()).toMatchSnapshot();
      });
    
      it('should find the button via testId', () => {
        const testIdName = 'pressMeButton';
    
        const {getByTestId} = render(<App />);
    
        const foundButton = getByTestId(testIdName);
    
        expect(foundButton).toBeTruthy();
      });
    
      it('should find the button via accessibilityLabel', () => {
        const accessibilityLabel = 'Press me';
    
        const {getByA11yLabel} = render(<App />);
    
        const foundButton = getByA11yLabel(accessibilityLabel);
    
        expect(foundButton).toBeTruthy();
      });
    
      it('should find the button title', () => {
        const title = 'Press me!';
    
        const {getByText} = render(<App />);
    
        const foundButtonTitle = getByText(title);
    
        expect(foundButtonTitle.props.children).toEqual(title);
      });
    });
    

    Ok, you know what time it is! Run the tests!

    You should see this:

    Summary

    And that wraps it up! In this post, we walked through the process of adding a button. Then, we wrote our first test and addressed how to update when a test fails using -u. Finally, we wrote a test using acessibilityLabel, and we also learned how to find a button title.

    In the next part of this series, we will go over Styles Testing. Stay tuned!

    [Editor’s Note: Never miss a post by subscribing to receive new blogs by email. No spam, opt-out anytime.]
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments