hasTextContent function Matchers

Matcher hasTextContent(
  1. [dynamic expected,
  2. bool normalizeWhitespace = true]
)

Allows you to check whether an element has the expected text content or not.

When a String argument is passed through, it will perform a whole case-sensitive match to the element content.

The whitespace of the element content is normalized unless you set normalizeWhitespace to false.

To perform a partial or case-insensitive match, you can use any of the string matchers like contains, or construct a RegExp with caseSensitive set to false.

Similar to jest-dom's toHaveTextContent matcher.

Examples

<button>Text Content</button>
import 'package:react/react.dart' as react;
import 'package:react_testing_library/matchers.dart' show hasTextContent;
import 'package:react_testing_library/react_testing_library.dart' as rtl;
import 'package:test/test.dart';

main() {
  test('', () {
    // Render the DOM shown in the example snippet above
    final view = rtl.render(react.button({}, 'Text Content'));

    // Use react_testing_library queries to store references to the node(s)
    final button = view.getByRole('button');

    // Use the `hasTextContent` matcher as the second argument of `expect()`
    expect(button, hasTextContent('Text Content'));
    expect(button, hasTextContent(RegExp(r'Content$'))); // to match partially
    expect(button, hasTextContent(RegExp('content', caseSensitive: false))); // to use case-insensitive match
    expect(button, isNot(hasTextContent('foo')));
    expect(button, hasTextContent()); // Will match a non-empty description
  });
}

NOTE: render() supports React vDom elements / custom components created using either the react or over_react packages.

The examples shown here use the react package since the react_testing_library does not have a direct dependency on over_react - but both libraries are fully supported.

Implementation

// ignore: avoid_positional_boolean_parameters
Matcher hasTextContent([dynamic expected, bool normalizeWhitespace = true]) =>
    _HasTextContent(expected, normalizeWhitespace: normalizeWhitespace);