DEV Community

Lekshmi Chandra
Lekshmi Chandra

Posted on

8 2

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay