hasValue function Null safety Matchers

Matcher hasValue(
  1. [dynamic value]
)

Allows you to check whether the given form element has the specified value.

It accepts <input>, <select> and <textarea> elements with the exception of <input type="checkbox"> and <input type="radio">, which can be meaningfully matched only using isChecked or hasFormValues.

For all other form elements, the value is matched using the same algorithm as hasFormValues does.

Similar to jest-dom's toHaveValue matcher.

Examples

<form>
  <input type="text" name="username" value="jane.doe" />
  <input type="number" name="age" value="35" />
  <input type="text" name="occupation" />
  <select multiple name="options">
    <option value="first">First Value</option>
    <option value="second" selected>Second Value</option>
    <option value="third" selected>Third Value</option>
  </select>
</form>
import 'package:react/react.dart' as react;
import 'package:react_testing_library/matchers.dart' show hasValue;
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.form({},
      react.input({'type': 'text', 'aria-label': 'username', 'value': 'jane.doe'}),
      react.input({'type': 'number', 'aria-label': 'age', 'value': '35'}),
      react.input({'type': 'text', 'aria-label': 'occupation'}),
      react.select({'multiple': true},
        react.option({'value': 'first'}, 'First Value'),
        react.option({'value': 'second', 'selected': true}, 'Second Value'),
        react.option({'value': 'third', 'selected': true}, 'Third Value'),
      ),
    ));

    // Use react_testing_library queries to store references to the node(s)
    final textInput = view.getByRole('textbox', name: 'username');
    final numberInput = view.getByRole('spinbutton', name: 'age');
    final emptyInput = view.getByRole('textbox', name: 'occupation');
    final selectInput = view.getByRole('listbox');

    // Use the `hasValue` matcher as the second argument of `expect()`
    expect(textInput, hasValue('jane.doe'));
    expect(textInput, hasValue(startsWith('jane.')));
    expect(numberInput, hasValue(35));
    expect(emptyInput, hasValue(''));
    expect(selectInput, hasValue(['second', 'third']));
    expect(selectInput, isNot(hasValue(['first'])));
  });
}

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 hasValue([dynamic value]) => _HasValue(value);