Automated tests give you confidence in the piece of code you write. Sometimes we write code that works locally then push to production. However, changes made breaks entirely different parts of the project.

Someone else on your team might have written these parts of the project, but your changes caused conflicts. Testing prevents this.

There are different types of tests: unit tests, integration tests, functional tests, end-to-end tests, and many more.

What is unit testing?

Using a car as an analogy, we all know that a car comprises of different components (Unless you live in a tree 🤪). These components comprise wheels, an engine, headlights, and taillights, etc.

Unit tests basically ensure each individual component performs as expected. Looking at our car analogy, to ensure our wheel is perfectly round we rotate it by exerting external force, same way we write unit tests to ensure individual components of our source code (software) function as they ought to.

In this article, we will be looking at the basic principles of unit tests with a simple react-native Button component.

Let’s go ahead to create a Button component.

import React from 'react';
import {Pressable, Text, View, StyleSheet} from 'react-native';

const Button = ({onPress, title, isLoading, transparent}) => {
  return (
    <Pressable
      onPress={() => {
        if (!isLoading) {
          return onPress();
        }
      }}>
      <View style={transparent ? styles.transparentBtn : styles.btn}>
        <Text style={transparent ? styles.transparentTitle : styles.title}>
          {isLoading ? 'Loading...' : title}
        </Text>
      </View>
    </Pressable>
  );
};

const styles = StyleSheet.create({
  btn: {
    width: '100%',
    height: 50,
    backgroundColor: '#74B3CE',
    alignItems: 'center',
    justifyContent: 'center',
    marginVertical: 10,
    borderRadius: 4,
  },
  transparentBtn: {
    width: '100%',
    height: 50,
    backgroundColor: 'transparent',
    alignItems: 'center',
    justifyContent: 'center',
    marginVertical: 10,
  },
  title: {
    color: 'white',
    fontSize: 16,
  },
  transparentTitle: {
    color: '#74B3CE',
  },
});

export default Button;

#react-native #unit-testing #test-automation #introduction #react #getting-started #jest #enzyme

Beginners Guide to Get Started with Unit Testing in React Native
1.35 GEEK