Render, debug

  1. Simple reusable rendering method

    In this method, we pass in the component as a parameter:

    1
    2
    3
    4
    5
    function 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
    12
    function 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
    3
    const div = document.createElement('div') // old is replaced.
    ReactDOM.render(<FavoriteNumber />, div)
    const {getByLabelText} = getQueriesForElement(div)


  1. Using the built-in render method

    Actually, the render method already exists in the react testing library.

    1
    import {render} from '@testing-library/react'


  1. Use debug to find errors

    debug and debug() 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
    7
    test('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)
    })


Share