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

Viewed 9445

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.
1 Answers

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();
});
Related