React testing library, how to get text from element

Viewed 3992

I'm trying to test a table being built using react testing library

I'm using debug which outputs

<body>
    <div>
      <div
        class="table-wrapper"
      >
        <div
          class="table-component__header"
        />
        <table
          class="test-table"
        >
          <tbody>
            <tr>
              <td
                class="text-grid-item"
                data-testid="text-grid-item"
              >
                test table data
              </td>
            </tr>
          </tbody>
          <tfoot
            class="table_footer"
          >
            <tr>
              <td />
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
</body>

I'm trying to assert test table data is there with

expect(findByTestId('text-grid-item')).toHaveTextContent('test table dat')

but it fails with

received value must be a Node.
Received has type:  object
Received has value: {}  

How can I assert the text test table data is there

import React from 'react'
import { render } from '@testing-library/react'
import { Table } from './table'

const givenTableWithElement = (test: Array<TableElement>) => {
    const table = {
        tableEntries: [{ tableElements: test }],
        type: 'table',
        tableType: 'test'
    }
    return table
}

describe('Components should render depending on their prop type', () => {

    test('Given table element is text, when rendered, text table class should be returned', () => {
        const imageTableTest: TableProps = givenTableWithElement([
            {
                text: 'test table data',
                display: {
                    mobile: true,
                    wrap: false
                }
            }
        ])

        const { debug } = render(<Table {...imageTableTest} />)
        debug()

        const { getByTestId } = render(<Table {...imageTableTest} />)

        expect(findByTestId('text-grid-item')).toHaveTextContent('test table dat')
    })

})
1 Answers

You can just do getByText('test table data') without asserting anything.

getByText will fail your test if it cannot find the text it is looking for. If the text is there and your test passes, you essentially asserted that it is there even if you haven't used expect() assertion explicitly. Though be careful when using queryByText (or any other react-testing-library method that starts with query), using that will return null, so if it can't find the text it is looking for it won't fail you test and you will get a false positive.

If you still want to use an expect you can try doing something like:

const gridItemText = getByTestId('text-grid-item').innerHTML
expect(gridItemText).toBe('test table data')
Related