How to test if a component is rendered or not by jest and enzyme?
Asked Answered
C

1

7

I am trying to learn tdd in react. I have a parent component which gets props from app component and based on the props render either child1 component or child2 component. Here are my react files:

App.js

import './App.css';
import Parent from './Parent';

function App() {
  return (
    <div className="App">
      <Parent number={"one"} word={"hello"}/>
      {/* can be one or two */}
    </div>
  );
}

export default App;

Parent.js

import React from 'react';
import Child1 from './Child1';
import Child2 from './Child2';

function Parent({number,word}) {
  return (
    <div className="Parent" data-testid="parent-test">
      {number === 'one' &&
        <Child1 />
      }
      {number === 'two' &&
        <Child2/>
      }
    </div>
  );
}

export default Parent;

child1.js

import React from 'react';

function Child1() {
  return (
    <div>
      I am Child1
    </div>
  );
}

export default Child1;

child2.js

import React from 'react';

function Child2() {
  return (
    <div>
      I am Child2
    </div>
  );
}

export default Child2;
`

How can I write a test using Jest and enzyme to check in parent file based on props if child1 is rendered or not.
Charlot answered 3/9, 2021 at 22:46 Comment(0)
M
20

You shouldn't check if your child component is rendered or not, but check for the actual rendered content (which the testing library encourage you to do)

For testing it in react-testing-library you could do something like this:

test("If Child1 is rendered!", () => {
  const { getByText } = render(<Parent number="one" word="hello" />);
  expect(getByText("I am Child1")).toBeInTheDocument();
});
Metagenesis answered 4/9, 2021 at 3:5 Comment(3)
I see your point thanks for that! cheers :)Charlot
This is not always desirable. Imagine you are rendering a link. Testing for the rendered text of the link, does not test if it is indeed a link.Blackguard
I want to test if a certain component is being re-render unnecessarily. What should I do?Heywood

© 2022 - 2024 — McMap. All rights reserved.