Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test that another component is rendered on button click ReactJS

I have two separate components in two different files

ComponentA and ComponentB

I have a button in ComponentB

Now I wish to test that when a particular button in ComponentB is clicked, ComponentA should be rendered as below:

import { render, screen, fireEvent } from '@testing-library/react';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB'

test('Component A Comes up on Click of Component B button', () => {
  render(<ComponentB />);

  const componentBButton = screen.getByRole('button');
  
  fireEvent.click(componentBButton);
  
  expect(<ComponentA />).toBeInTheDocument(); //This throwing an error that receiver must be HTMLElement or SVGElement

});

Unfortunately, I am getting this error Receiver must be HTMLElement or SVGElement on the expect(<ComponentA />).toBeInTheDocument(); line

Please, I'm new to testing, how can I solve this? Thank you for your input

like image 366
ololo Avatar asked May 25 '26 19:05

ololo


1 Answers

UI testing is meant to test the rendered output, not the internal structure of your code. In other words, you should not test that a component was rendered, but instead you should test that something rendered by that component is on the screen.

For example, if ComponentA renders an h1 tag with text content "hello world", you would want to test that that tag or text is in the document.

Here's a simplified example.

ComponentA

const ComponentA = () => <h1>hello world</h1>

ComponentB

const ComponentB = () => (
  <div>
    <p>My App</p>
    <ComponentA />
  </div>
);

Test

test('hello world is rendered to the screen', () => {
  render(<ComponentB />);
  
  // Asserts that the HTML ComponentA produces was actually rendered
  expect(screen.findByText('hello world')).toBeInTheDocument();
});
like image 172
Brian Thompson Avatar answered May 27 '26 07:05

Brian Thompson