Asserting a style of a parent element - There is a better way of doing this?
cassiourugit opened this issue · 2 comments
Hi,
I'm able to find my icon and validate the opacity by doing it like this:
const rightIcon = getByTestId('SvgPlusIcon');
expect(rightIcon.parent?.parent?.parent?.parent).toHaveStyle({opacity: pfTheme.opacity.light});
I've looked everywhere, and couldn't find a better way of doing this instead of:
rightIcon.parent?.parent?.parent?.parent
Anyone knows how to get to the parent element in a more elegant way?
Sorry about my English, not a native speaker...
@cassiourugit I feel your pain. The element tree returned by React Native Testing Library is composed from ReactTestInstance
objects, which represent either host components (e.g. View
, RNSVGSvgView
) or composite components (function/class components, from your own code, imported libraries, even React Native itself). Using simple element.parent
can give you both host and composite components depending on the component tree structure.
As a kind of recommended workaround you could create a helper function:
function getHostParent(element: ReactTestInstance) {
let result = element.parent;
while (typeof result.type !== 'string') {
result = result.parent;
}
return result;
}
Passing rightIcon
to it, you should receive host View
instance to match the styles as you need:
const hostParent = getHostParent(rightIcon);
expect(hostParent).toHaveStyle({opacity: pfTheme.opacity.light});
Closing as solved because of suggested workaround.