I'm getting the hang of @testing-library/react
and testing in general, but I'm confused on how to achieve 100% coverage via jest
on the usage of useRef
where we want to run a side effect or even a function body that is triggered on the condition that ref.current
exists. In my context, I only care if the component is rendered and that's when I perform my dom mutations on the dom elements. I know it's not ideal, but it's the use case that I'm facing by using another library.
Here's a simple component demonstrating my issue:
export const Test: React.FC<TestProps> = ({text}) => {
const ref = React.useRef<HTMLDivElement>(null);
React.useLayoutEffect(() => {
if (ref.current !== null) { // this is line 11 which is not covered according to jest below
const span = ref.current.getElementsByTagName('span')[0];
span.setAttribute('data-test', 'attribute has been set');
}
}, [ref.current]);
return (
<div ref={ref}>
<span>{text}</span>
</div>
);
};
And here's the test. I know that there are recommended queries provided by screen
such as getByRole
, but libraries that are poorly labeled/tagged force me to rely on the more traditional enzyme
method of using classic document queries to target elements that I need to mutate and assert against.
it('renders and sets attribute', () => {
const {container} = render(<Test text="hello" />);
expect(container.getElementsByTagName('span')[0]).toHaveAttribute(
'data-test',
'attribute has been set'
);
});
The test actually passes, which means the side effect was run and asserted. When the test runs, ref.current
is true and the side effect is applied via useLayoutEffect
. I've heard that asserting the side effect should work and count as coverage, but that's not what I'm seeing. I've also heard that it's possible that I need to rerender the component to be able to confirm coverage of the logic, but using RTL's rerender
didn't do anything either.
Getting the coverage via jest shows:
-------------------------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------------------------------|---------|----------|---------|---------|-------------------
components/Test | 100 | 50 | 100 | 100 |
Test.tsx | 100 | 50 | 100 | 100 | 11
Any help would be appreciated. I searched everywhere, but couldn't figure out how to address this use case where I want test coverage on the condition/branch that ref.current
exists, where the ref
is attached to a dom element. Perhaps this isn't the correct paradigm I'm thinking in?
question from:
https://stackoverflow.com/questions/65650837/how-to-achieve-test-coverage-of-ref-current-usage 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…