loading...

Test for 'element exists?'- React testing library

lek890 profile image Lekshmi Chandra ・1 min read

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>
  );
};

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

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

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

Posted on by:

Discussion

pic
Editor guide