getInstance method
ReactComponent
getInstance()
Returns the mounted React composite component instance.
If you are rendering a function component using mount, calling getInstance will throw a
StateError
.
If you are trying to access an instance of some other component rendered by the function component, then try either:
i. Wrapping the component in a class-based wrapper component (such as the
Wrapper
component exported by over_react_test):final jacket = mount(Wrapper()( YourFunctionComponent()(), ));
ii. UsinguiForwardRef
or a ref prop to pass a ref through to the component you needIf you are trying to access / query for a DOM node rendered by the function component, try using:
queryByTestId(jacket.mountNode, yourTestId)
Implementation
ReactComponent getInstance() {
// [1] Adding an additional check for dom components here because the current behavior when `_renderedInstance` is
// a DOM component (Element) - does not throw. The cast to `ReactComponent` - while not "sound", is harmless
// since it is an anonymous JS interop class - not a Dart type.
if (!_isCompositeComponent && /*[1]*/!_isDomComponent) {
throw StateError(over_react.unindent('''
getInstance() is only supported when the rendered object is a composite (class based) component.
If you are rendering a function component, and are trying to:
1. Access an instance of some other component rendered by it, then try either:
i. Wrapping the component in a class-based wrapper component (such as the `Wrapper` component exported by over_react_test):
final jacket = mount(Wrapper()(
YourFunctionComponent()(),
));
ii. Using `uiForwardRef` or a ref prop to pass a ref through to the component you need
2. Access / query for a DOM node rendered by the function component, then try using `queryByTestId` with `mountNode`:
queryByTestId(jacket.mountNode, 'yourTestId')
'''));
}
return _renderedInstance as ReactComponent;
}