DEV Community

Lekshmi Chandra
Lekshmi Chandra

Posted on

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

Top comments (0)