How can I test inner text of a div element

Viewed 10386

I'm trying to find the best practice to test textContent for a div element here, using react testing library.

Say I'd like to test this simple react component to see if {props.text} is rendered properly on the HTML DOM.

const Simple = props => (
  <>
    <div> {props.text} </div>
    <div> test text </div>
  </>
);

I've tried to use getByText, then test expect(getByText('text passed as prop')).toBeDefined() but it didn't seem to work properly.

It must be much easier if I add a className or id for the first <div /> then probably I can just go for querySelector, but what if I didn't want to add any HTML attribute here? How can I locate this element properly?

Is there any solution to find the first element that has no attribute and test its inner text?

1 Answers

It works for me using "@testing-library/react": "^9.4.0". E.g.

index.tsx:

import React from 'react';

const Simple = (props) => (
  <>
    <div> {props.text} </div>
    <div> test text </div>
  </>
);

export { Simple };

index.test.tsx:

import React from 'react';
import { Simple } from './';
import { render } from '@testing-library/react';

describe('60534908', () => {
  it('should find div element', () => {
    const mProps = { text: 'text passed as prop' };
    const { getByText } = render(<Simple {...mProps} />);
    expect(getByText('text passed as prop')).toBeDefined();
    expect(getByText('test text')).toBeDefined();
  });
});

Unit test results with 100% coverage:

 PASS  stackoverflow/60534908/index.test.tsx (8.606s)
  60534908
    ✓ should find div element (37ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.784s, estimated 11s
Related