6

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

Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
ololo
  • 1,326
  • 2
  • 14
  • 47

2 Answers2

4

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();
});
Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
1

The expect function can only be a DOM element rather than a React component.

You could check to see if <ComponentA> is in the document by identifying it after the fireEvent.click(componentBButton) call. Does it have an id or any other unique attribute?

Let's imagine below is the definition of <ComponentA>:

const ComponentA = () => {
  return (
    <div id="component_a">Hello World</div>
  );
}

We can now identify it using the component_a id and passing that to our expect function:

expect(document.getElementById("component_a")).toBeInTheDocument();
aaimio
  • 186
  • 1
  • 6