react-testing-library icon indicating copy to clipboard operation
react-testing-library copied to clipboard

How to check if a component contains instance of another component?

Open quangta93 opened this issue 7 years ago • 19 comments

I'm wondering what's the best practice to check whether my testing component contains one or multiple instances of another component. The ideal scenario looks something like this:

// Component
export const AppHeader = () => (
  <nav data-testid="app-header">
    <Clock />
  </nav>
);

// Component.test.js
test('AppHeader renders a <Clock />', () => {
  const { getByTestId } = render(<AppHeader />);
  expect(getByTestId('app-header')).toContainInstanceOf(<Clock />);
});

Snapshot testing obviously doesn't work because the value of Clock keeps changing whenever we render AppHeader. Another potential solution is to set data-testid for my Clock component but in that case, how can we test the exact number of Clock rendered by AppHeader? With a clock ID, it'd require to pass data-testid as props into Clock because data-testid doesn't work on custom components.

quangta93 avatar Dec 19 '18 21:12 quangta93

With a clock ID, it'd require to pass data-testid as props into Clock because data-testid doesn't work on custom components.

It is possible to assign the top level element a test-id though. One example could be:

const Clock = props => (
  <time data-testid={props["data-testid"]}>
      {/* clock code */}
  </time>
)
// Component
export const AppHeader = () => (
  <nav data-testid="app-header">
    <Clock data-testid="clock" />
    <Clock data-testid="clock" />
    <Clock data-testid="clock" />
  </nav>
);

// Component.test.js
test('AppHeader renders a <Clock />', () => {
  const { getAllByTestId, getByTestId } = render(<AppHeader />);
  const appHeader = getByTestId('app-header')
  const clocksInHeader = within(appHeader).getAllByTestId('clock')
  expect(clocksInHeader.length).toBe(3);
});

Live Example

Docs:

LukasWerfel avatar Dec 24 '18 18:12 LukasWerfel

If the component is third-party and you can't modify it to accept a prop, you can use a Jest mock to wrap or replace the component:

// AppHeader.js
import Clock from 'clock';

export default function AppHeader () {
  return (
    <div>
      <Something />
      <Clock />
    </div>
  );
}
// AppHeader.test.js
import {within, render} from 'react-testing-library';
import Clock from 'clock';
const ActualClock = jest.requireActual('clock');
jest.mock('clock', () =>
  <div data-testid="clock">
    <ActualClock />
  </div>
);

test('AppHeader renders a <Clock />', () => {
  const { getAllByTestId, getByTestId } = render(<AppHeader />);
  const appHeader = getByTestId('app-header');
  const clocksInHeader = within(appHeader).getAllByTestId('clock');
  expect(clocksInHeader.length).toBe(3);
});

Using requireActual is optional; if you don't care what Clock renders you can just mock it with a div containing a testid.

The downside of using mocks instead of adding testids to components in your actual app is that if you decide to switch to a different clock component, or replace it with an inline helper component, the test may break unnecessarily; i.e., if the test is saying "there should be 3 clocks of any kind", using testids in the app code lets the app decide what component represents a clock, whereas mocking is tied to that specific module. Enzyme-style find(MyComponent) has the same problem.

alexkrolick avatar Dec 30 '18 21:12 alexkrolick

Enzyme have more specific API to check how many times children component rendered into DOM. With react-testing-library I'm not sure Is there any kind API exist for covering this use case. For this use case, I always mock react component and pass through props.

Header.jsx

import React, { Component } from 'react'

class Header extends Component {
  render() {
    const { Clock } = this.props
    return (
      <div>
        <Clock />
        <Clock />
        <Clock />
      </div>
    )
  }
}

Clock.jsx

import React from 'react'

const Clock = (props) => <div>real clock time: {Date.now()}</div>

export default Clock

Header.test.js

import React from 'react'
import { render, cleanup } from 'react-testing-library'
import 'jest-dom/extend-expect'
import Header from '../Header'

afterAll(cleanup)

test('should render clock twice', () => {
  const mockClock = jest.fn(() => <div>mocked clock time: {Date.now()}</div>)
  // eslint-disable-next-line no-unused-vars
  const { debug } = render(<Header Clock={mockClock} />)
  expect(mockClock).toBeCalledTimes(3)
})

sagar-gavhane avatar Jan 03 '19 18:01 sagar-gavhane

Whatever ends up happening here, we're not going to implement anything within react-testing-library to assert whether certain components were rendered or how many times they were rendered. That's an implementation detail.

Thanks for the tips from people though!

kentcdodds avatar Jan 03 '19 20:01 kentcdodds

I'm totally agree 👍 with @kentcdodds. Don't write tests for component implementation details.

sagar-gavhane avatar Jan 04 '19 03:01 sagar-gavhane

Whatever ends up happening here, we're not going to implement anything within react-testing-library to assert whether certain components were rendered or how many times they were rendered. That's an implementation detail.

Thanks for the tips from people though!

Can you explain how is testing whether a component was rendered on an implementation detail? If the user clicks a button and its job is to render a popup, shouldn't I be testing that the popup was rendered? Especially since its something the end user will be seeing on screen.

ZeroDarkThirty avatar Oct 18 '19 06:10 ZeroDarkThirty

The user can't tell there is a React component named "Popup", just the HTML output of it

alexkrolick avatar Oct 18 '19 15:10 alexkrolick

The user can't tell, but I do, and when I use TDD, I don't even know what the "Popup" component will contain as it's not even written yet. I think there should be something for this.

lcoenen avatar Mar 15 '20 16:03 lcoenen

You can mock it with jest.mock if that's what your want to do

kentcdodds avatar Mar 15 '20 19:03 kentcdodds

You can mock it with jest.mock if that's what your want to do

@kentcdodds Hi. How can i test my components with full coverage (100% in codecov by example)?

Other complexity: mocking of components that are used as children causes the tests not to fail when the component implementation changes.

krutoo avatar Sep 22 '20 05:09 krutoo

Other question: how can i check that my component is using the child component correctly?

Example

import React from 'react';
import SomeButton from 'third-party-components';

const MyComponent = ({ onClick }) => (
  <div>
    <SomeButton 
      onClick={event => {
        console.log('some effect here...');
        onClick(event); // just call callback
      }}
    >Say hello!</SomeButton>
  </div>
);

I need to check that the spy function passes to onClick is called exactly when someone clicked on SomeButton.

But I can't just find the button in the tree and cause it to click, for example because the component is implemented like this:

export const SomeButton = ({ children, onClick }) => {
  const ref = useRef();

  useEffect(() => {
    // <SomeButton /> handles clicks of some other element on page (with dynamic query)
    const targetElement = document.body.querySelector(`.item[data-id=${Math.random()}]`);

    targetElement.addEventListener('click', onClick);

    return () => targetElement.removeEventListener('click', onClick);
  }, [onClick]);

  return (
    <button ref={ref}>{children}</button>
  );
};

SomeButton component encapsulates information about which element will actually be listened to clicks

In this case I don't need to test the markup. I need to test how my component interacts with the environment via a channel provided by a third party component.

Writing mocks every time for such cases is a rather laborious task. Essentially, as a developer, I should just fix the interaction of my component with the child.

I can of course write a smart mock that wraps the original component without changing its behaviour. But that means considering implementation details in test environment.

It also creates problems when a third-party component is used in several projects: you will have to put mocks in a separate package or copy them in each project. In any case, you will have to monitor the relevance of this mock.

krutoo avatar Sep 22 '20 07:09 krutoo

Whatever ends up happening here, we're not going to implement anything within react-testing-library to assert whether certain components were rendered or how many times they were rendered. That's an implementation detail. Thanks for the tips from people though!

Can you explain how is testing whether a component was rendered on an implementation detail? If the user clicks a button and its job is to render a popup, shouldn't I be testing that the popup was rendered? Especially since its something the end user will be seeing on screen.

Totally agree. Sometimes we only need (should) to test that we're using the API of another component as expected. For instance, if I'm using a modal component, I only should test that I've set its opened prop or called its open() method if that would be the case. What I shouldn't do is to test that effectively the modal is displaying correctly (is not my job and we suppose that the modal works as it says). But it seems that there is no way to achieve that with react-testing-library.

kcmr avatar Apr 08 '21 21:04 kcmr

dawg yall trippin lemme test if a component is in a component

salil-khanna avatar Apr 14 '22 16:04 salil-khanna

My struggle was: I have 4 buttons in a component and they all have the same CTA Edit, although their placement in the component indicates what information you are actually editing. They all have the same on click handler so i used getAllByText to get all the things then tested the behavior of one of them.

  test('selected modal changes if edit action selected', () => {
    const button = screen.getAllByText('Edit')[0];
    fireEvent.click(button);

    expect(props.setActiveModal).toHaveBeenCalledTimes(1);
  });

bleonardio avatar Jun 06 '22 19:06 bleonardio

Whatever ends up happening here, we're not going to implement anything within react-testing-library to assert whether certain components were rendered or how many times they were rendered. That's an implementation detail. Thanks for the tips from people though!

Can you explain how is testing whether a component was rendered on an implementation detail? If the user clicks a button and its job is to render a popup, shouldn't I be testing that the popup was rendered? Especially since its something the end user will be seeing on screen.

Totally agree. Sometimes we only need (should) to test that we're using the API of another component as expected. For instance, if I'm using a modal component, I only should test that I've set its opened prop or called its open() method if that would be the case. What I shouldn't do is to test that effectively the modal is displaying correctly (is not my job and we suppose that the modal works as it says). But it seems that there is no way to achieve that with react-testing-library.

Quoting myself… I have to say that I've changed my mind since I wrote this and now I totally agree that this is testing the implementation and RTL does a great job offering the tools to avoid that. If you write the same application using different technologies, let's say, the typical ToDo app, ideally you shouldn't need to change the tests for the same behavior.

kcmr avatar Jun 06 '22 19:06 kcmr

@bleonardio - Keep in mind that taking the first element is also an implementation detail :) I'd suggest giving a test-id or even better, fetching the container of that edit button by a meaning and run within :)

MatanBobi avatar Jun 07 '22 14:06 MatanBobi

An alternative, if you are willing to test the so called implementation details, would be to use the returned container property in the render to do the checks. The container is an HTMLElement (should depend on what your component renders) and therefore you are able to use it's full API.

As an example, If you for instance know what is the class you want to search for (not exactly what is being asked but a bit more hacky) would be to do:

const { container } = render(...);
expect(container.querySelector('.SOME_CSS_CLASS_HERE')).not.toBe(null);

rleira avatar Nov 02 '22 22:11 rleira

(i know this thread has been closed for a while, but i find myself migrating from enzyme and running into this.)

Surely querying by data-testid is just as non user-centric as querying by react component? if anything, you could say it's even less user centric because at least a react component probably has some clear semantic meaning that a user woud recognise whereas a randomly tagged div could correspond to anything (and who knows if it's meaning has drifted since the data test id was first added).

So i don't get why the library would offer one and not the other (given that enzyme didn't require data-testids, and it's nice to not have to litter component implementation with machinery that's just there for the sake of tests).

d1manson avatar Sep 12 '24 10:09 d1manson

@d1manson querying by data-testid should always be a last resort when no other option is available. It’s better to prioritize querying by role (semantics), by text, etc. Playwright is taking the same approach for e2e tests.

This section of the documentation explains the philosophy of Testing Library really well: https://testing-library.com/docs/queries/about/#priority

I had the same dilemma when I first started using Testing Library until something clicked in my mind, and I understood that the components I’m using are an implementation detail.

kcmr avatar Sep 12 '24 10:09 kcmr