tab static method

void tab({
  1. bool shift = false,
  2. Element? focusTrap,
})

Fires a tab event changing the document.activeElement in the same way the browser does.

See: testing-library.com/docs/ecosystem-user-event/#tabshift-focustrap

Options

shift

Default: false

Set shift to true to invert the tab direction.

focusTrap

Default: HtmlDocument.body

Set focusTrap to restrict the tabbing within a certain container.

Example

<div>
  <input />
  <div data-test-id="container">
    <input />
    <input />
  </div>
</div>
import 'dart:html';

import 'package:react/react.dart' as react;
import 'package:react_testing_library/matchers.dart' show isFocused;
import 'package:react_testing_library/react_testing_library.dart' as rtl;
import 'package:react_testing_library/user_event.dart';
import 'package:test/test.dart';

void main() {
  test('', () {
    // Render the DOM shown in the example snippet above.
    final view = rtl.render(react.div({}, [
      react.input({}),
      react.div({
        'data-test-id': 'container'
      }, [
        react.input({}),
        react.input({}),
      ]),
    ]));

    // Use react_testing_library queries to store references to the nodes.
    final inputs = view.getAllByRole('textbox');
    final container = view.getByTestId('container');

    // Use `isFocused` matcher to verify the currently focused element.
    expect(document.body, isFocused);

    UserEvent.tab();
    expect(inputs.first, isFocused);

    UserEvent.tab();
    expect(inputs[1], isFocused);

    UserEvent.tab();
    expect(inputs[2], isFocused);

    UserEvent.tab();
    expect(document.body, isFocused, reason: 'Cycle goes back to the body element.');

    // Shifts the focus backwards.
    UserEvent.tab(shift: true);
    expect(inputs[2], isFocused);

    // Cycles focus within the container.
    UserEvent.tab(focusTrap: container);
    expect(inputs[1], isFocused);
  });
}

Warning About Errors

Unlike the JS API, any uncaught errors thrown during event propagation will get rethrown. This helps surface errors that could otherwise go unnoticed since they aren't printed to the terminal when running tests.

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.

{@category UserActions}

Implementation

static void tab({bool shift = false, Element? focusTrap}) {
  final options = {
    'shift': shift,
    if (focusTrap != null) 'focusTrap': focusTrap,
  };
  eventHandlerErrorCatcher(() {
    getProperty(_userEvent, 'tab')(
      jsifyAndAllowInterop(options),
    );
  });
}