hasAttribute function Null safety Matchers

Matcher hasAttribute(
  1. String attribute,
  2. [dynamic valueOrMatcher = isNotNull]
)

Allows you to check whether an element has an attribute that matches the provided valueOrMatcher or not.

You can also optionally use a Matcher as the valueOrMatcher to do partial string matching (e.g. using contains(), startsWith(), endsWith(), etc).

Similar to jest-dom's toHaveAttribute matcher.

Examples

<button type="submit" aria-label="Submit the form">ok</button>
import 'package:react/react.dart' as react;
import 'package:react_testing_library/matchers.dart' show hasAttribute;
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({'type': 'submit', 'aria-label': 'Submit the form'}, 'ok'),
    );

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

    // Use the `hasAttribute` matcher as the second argument of `expect()`
    expect(button, hasAttribute('type', 'submit'));
    expect(button, isNot(hasAttribute('type', 'button'))));
    expect(button, hasAttribute('aria-label', contains('Submit')));
    expect(button, hasAttribute('type', isNot(contains('but'))));
    expect(button, hasAttribute('aria-label')); // Shorthand for `hasAttribute('aria-label', isNotNull)`
  });
}

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

Matcher hasAttribute(String attribute, [dynamic valueOrMatcher = isNotNull]) =>
    _ElementAttributeMatcher(attribute, valueOrMatcher);