I have a component which I am trying to test -
export const Block = ({ title }) => {
const [isSmall, setIsSmall] = useState(false);
reutrn (
<BlockContainer
onBlockContainerResize={(width: number) => (width < 180 ? setIsSmall(true) : setIsSmall(false))}
>
<div className={isSmall ? 'title--small' : 'title'} data-testid={isSmall ? 'isSmall' : ''}>
{title}
</div>
<div className={isSmall ? 'desc--small' : 'desc'}>
{desc}
</div>
</BlockContainer>
)
}
I added a data-testid as I want to avoid testing classNames as this goes against react-testing-library principles. I just want to make sure that if the container is below 180px, then isSmall is set to true.
For my test I am using a div as the container rather than the parent component BlockContainer -
test('should set isSmall to true if container width is below 180px', () => {
render(
<div style={{ width: '170px' }}>
<Block
title="test title"
desc="test description"
/>
</div>
);
expect(within(screen.getByTestId('isSmall')).queryByText('test title')).toBeInTheDocument();
});
However when trying this, isSmall is not being set to true and so the datatest-id is not being set. I am confused as to why this is happening?
Here is the BlockContainer implementation -
export const BlockContainer: FunctionComponent<BlockContainerProps> = ({
children,
onBlockContainerResize,
}) => {
const blockRef = useRef<HTMLDivElement>(null);
useResizeObserver(blockRef, (entry) => onBlockContainerResize?.(entry.contentRect.width));
return (
<div
ref={blockRef}
>
{children}
</div>
);
};