There are multiple ways of getting an element's text content: getByText
vs findByText
vs queryByText
.
Sometimes I get confused about which one to use.
I have the following example in react-native:
it('should render children', () => {
const mockedChildComponentTxt = 'Children are rendered';
const { getByText, findByText, queryByText } = render(
<MyProvider>
<div>{mockedChildComponentTxt}</div>
</MyProvider>,
);
expect(queryByText(mockedChildComponentTxt)).toBeTruthy()
});
queryByText
and getByText
are failing, but findByText
works.
debug()
resulting in:
<RNCSafeAreaView
onInsetsChange={[Function anonymous]}
style={
Object {
"flex": 1,
}
}
>
<div>
Children are rendered
</div>
</RNCSafeAreaView>
Why findByText
works in the above example, but getByText
and queryByText
fail?
getBy
throws an error if the element is not found, whilequeryBy
returns null if the element is not found. So, if you're checking for the presence of an element that might not be there, usequeryBy
. If you're certain the element should exist and want the test to fail if it doesn't, usegetBy
. – Partiality