Simple reusable rendering method
In this method, we pass in the component as a parameter:
1
2
3
4
5function render(ui) {
const div = document.createElement('div')
ReactDOM.render(<FavoriteNumber />, div)
getQueriesForElement(div)
}
But there is no return here. We need to return an object with all queries. At the same time, we’re going to rename the div to container and add it to return .
1
2
3
4
5
6
7
8
9
10
11
12function render(ui) {
const container = document.createElement('div')
ReactDOM.render(ui, container)
const queries = getQueriesForElement(container)
return {container, ...queries}
}
test('renders a number input with a label "Favorite Number"', () => {
const {getByLabelText} = render(<FavoriteNumber />)
const input = getByLabelText(/favorite number/i)
expect(input).toHaveAttribute('type', 'number')
})
In this code, we replace the previous three lines of code with render to make it generic.
1
const {getByLabelText} = render(<FavoriteNumber />) //new
1
2
3const div = document.createElement('div') // old is replaced.
ReactDOM.render(<FavoriteNumber />, div)
const {getByLabelText} = getQueriesForElement(div)
Using the built-in render method
Actually, the render method already exists in the react testing library.
1
import {render} from '@testing-library/react'
Use debug to find errors
debug
anddebug()
can be used anywhere, with or without arguments.debug()
can see what the DOM looks like at this node. E.g:1
2
3
4
5
6
7test('renders a number input with a label "Favorite Number"', () => {
const {getByLabelText, debug} = render(<FavoriteNumber />)
debug()
const input = getByLabelText(/favorite number/i)
expect(input).toHaveAttribute('type', 'number')
debug(input)
})