Test for 'element exists?'- React testing library

lek890

Lekshmi Chandra

Posted on February 19, 2020

Test for 'element exists?'- React testing library

Problem:

A react component is to being unit tested. The presence of an element after render is to be checked. In the following example, button with premium features is rendered conditionally.

Example:

const UserProfile: React.FC = user => {
  return (
    <div>
      <span>Hello {user.name}</span>
      {user.isPremiumUser && <button data-testid="premiumFeatures">Show premium features</button>}
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

Test cases:

1. Check for presence

import { render } from '@testing-library/react';

const { getByTestId } = render(
         <UserProfile user={{ name: 'Sheldon', isPremiumUser: false }} />
      );

expect(getByTestId('premiumFeatures')).toBeTruthy(); //passes

Enter fullscreen mode Exit fullscreen mode

2. Check for absence

When we use getByTestId to find an element and if it doesn't exist, getByTestId yells out an error which cannot be used to assert the absence.

import { render } from '@testing-library/react';

const { getByTestId } = render(
         <UserProfile user={{ name: 'Sheldon', isPremiumUser:false }} />
      );

expect(getByTestId('premiumFeatures')).toBeFalsy(); //fails with unable find element with testid msg

Enter fullscreen mode Exit fullscreen mode

So, what can be used here is queryByTestId.

import { render } from '@testing-library/react';

const { queryByTestId } = render(
         <UserProfile user={{ name: 'Sheldon', isPremiumUser: false }} />
      );

expect(queryByTestId('premiumFeatures')).toBeFalsy(); //passes

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
lek890
Lekshmi Chandra

Posted on February 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related