What is the best way to test a text in a div or a p tag in react-testing-library ?
Let's pretend that we have a react component as such :
const Greeting = ({name}) => {
return <div>Hello {name}!</div>
}
What would be the best way to test that the component renders the expected value, would it be using toBeInTheDocument() :
import {render, screen} from '@testing-library/react'
import Greeting from './greeting'
test('it renders the given name in the greeting', () => {
render(<Greeting name="John Doe"/>)
expect(screen.getByText(`Welcome John Doe!`)).toBeInTheDocument()
})
or using toBeVisible()
import {render, screen} from '@testing-library/react'
import Greeting from './greeting'
test('it renders the given name in the greeting', () => {
render(<Greeting name="John Doe"/>)
expect(screen.getByText(`Welcome John Doe!`)).toBeVisible()
})
or neither:
import {render, screen} from '@testing-library/react'
import Greeting from './greeting'
test('it renders the given name in the greeting', () => {
render(<Greeting name="John Doe"/>)
screen.getByText(`Welcome John Doe!`)
})
The last one makes more sense to me as if 'Welcome John Doe!' is not on the page, it will immediately fail whereas if it is on the page, the two first propositions would be equivalent to: expect(true).toBe(true)
am I missing something here?