DEV Community

Cover image for How to have different returns from the same mock with React Native + Jest
Everaldo Junior
Everaldo Junior

Posted on

2 1

How to have different returns from the same mock with React Native + Jest

1. Scenario

Let's imagine a react-native scenario where you have a component that has a text for users with active subscription and another text for users with inactive subscription.

Like the image below:
Image description

2. Dependencies

Make sure you have jest (min version 27.0.0) and react testing library for react native installed and updated.

If you don't, run the command below:

yarn add jest @testing-library/react-native @types/jest -D
Enter fullscreen mode Exit fullscreen mode

3. Implementation

This is how our function that returns if the user has a active subscription is implemented (but let's imagine that it is an endpoint or a library function).

export const auth = () => {
  return {
    user: {
      name: 'John Doe',
      email: 'johndoe@gmail.com',
      isSubscriptionActive: false,
    },
  };
};

Enter fullscreen mode Exit fullscreen mode

And this is how our component SubscriptionCard looks like:

import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {auth} from '../../services/api';

const SubscriptionCard = () => {
  const isSubscriptionActive = auth().user.isSubscriptionActive;
  return (
    <View style={styles.container}>
      <Text testID="subscription-card-label" style={styles.text}>
        {isSubscriptionActive ? 'Active' : 'Not Active'}
      </Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 48,
    borderRadius: 16,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#1565C0',
  },
  text: {
    fontWeight: 'bold',
    fontSize: 24,
    color: '#fff',
  },
});

export default SubscriptionCard;

Enter fullscreen mode Exit fullscreen mode

So we need to test if the text is "Active" when the auth() functions return isSubscriptionActive: true and "Not Active" when isSubscriptionActive: false.

For that, i will create a file named SubscriptionCard.spec.tsx

The first thing we need to do is use jest.mock in the path (or library name) of the function that we are using:

jest.mock('../../services/api');
Enter fullscreen mode Exit fullscreen mode

Now, we need to write the "skeleton" of our tests

describe('SubscriptionCard component', () => {
  it('text should be "Active" if subscription is active', () => {

  });

  it('text should be "Not Active" if subscription is not active', () => {

  });
});

Enter fullscreen mode Exit fullscreen mode

So now we just need to individually mock the return of auth() function like this:

    const authMocked = mocked(auth as any);

    authMocked.mockReturnValue({
      user: {
        isSubscriptionActive: true,
      },
    });
Enter fullscreen mode Exit fullscreen mode

For the first test

And like this:

    const authMocked = mocked(auth as any);

    authMocked.mockReturnValue({
      user: {
        isSubscriptionActive: true,
      },
    });
Enter fullscreen mode Exit fullscreen mode

For the second one.

And then we can call the expect function that we are testing, giving this final result:

import {render} from '@testing-library/react-native';
import React from 'react';
import {mocked} from 'jest-mock';
import SubscriptionCard from '.';
import {auth} from '../../services/api';

jest.mock('../../services/api');

describe('SubscriptionCard component', () => {
  it('text should be "Active" if subscription is active', () => {
    const authMocked = mocked(auth as any);

    authMocked.mockReturnValue({
      user: {
        isSubscriptionActive: true,
      },
    });

    const {getByTestId} = render(<SubscriptionCard />);
    const cardText = getByTestId('subscription-card-label');

    expect(cardText.children[0]).toBe('Active');
  });

  it('text should be "Not Active" if subscription is not active', () => {
    const authMocked = mocked(auth as any);

    authMocked.mockReturnValue({
      user: {
        isSubscriptionActive: false,
      },
    });

    const {getByTestId} = render(<SubscriptionCard />);
    const cardText = getByTestId('subscription-card-label');

    expect(cardText.children[0]).toBe('Not Active');
  });
});

Enter fullscreen mode Exit fullscreen mode

Github repository

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay