queryByTestId function

Element? queryByTestId(
  1. dynamic root,
  2. String value, {
  3. String key = defaultTestIdKey,
  4. bool searchInShadowDom = false,
  5. int? shadowDepth,
})

Returns the Element of the first descendant of root that has its key html attribute value set to a space-delimited string containing value.

Throws if root or findDomNode(root) is null. root is kept nullable for convenience, since the input to this function is often a dynamic component instance value.

Setting searchInShadowDom to true will allow the query to search within ShadowRoots that use mode:"open". shadowDepth will limit how many layers of ShadowDOM will searched. By default it will search infinitely deep, and this should only be needed if there are a lot of ShadowRoots within ShadowRoots.

Example:

// Render method for `Test` `UiFactory`:
render() {
  return (Dom.div()..addTestId('outer'))(
    (Dom.div()
      ..addProps(copyUnconsumedProps())
      ..addTestId('inner')
    )()
  );
}

// Within a test:
var renderedInstance = render((Test()..addTestId('value'))());

// Will result in the following DOM:
<div data-test-id="outer">
  <div data-test-id="inner value">
  </div>
</div>

queryByTestId(renderedInstance, 'value'); // returns the `inner` `<div>`

Related: queryAllByTestId, getComponentRootDomByTestId.

Implementation

Element? queryByTestId(dynamic root, String value, {String key = defaultTestIdKey, bool searchInShadowDom = false, int? shadowDepth}) {
  ArgumentError.checkNotNull(root, 'root');

  final node = findDomNode(root);
  if (node == null) {
    throw ArgumentError('findDomNode(root) must not be null. To use this function, your component must render DOM.');
  }

  var results = _findDeep(node, _makeTestIdSelector(value, key: key), searchInShadowDom: searchInShadowDom, findMany: false, depth: shadowDepth);
  return results.isNotEmpty ? results.first : null;
}