React Testing Library, Component can be found using component.getByText but not screen.getByText

39 Views Asked by At

I have a simple component I am testing (deliberately simplified to give a minimal reproducible example), where there is a behavior difference bewteen screen.getByText and the rendered element's getByText method

export const GuestGoPaperlessModal: React.FC<Props> = () => {
        return (
        <>
            <div className="flex justify-center">
                <Leaf size={40} spotColor="#C9DBFE" strokeWidth="0.5" aria-hidden="true"/>
            </div>
            <div className="font-serif text-primary-13126c">Simplify. Go paperless</div>
        </>
    )
}

I have the following test

render(<GuestGoPaperlessModal providerId={1} userPublicId="123"/>);
screen.getByText("Simplify. Go paperless")

It fails on the getByText with "TestingLibraryElementError: Unable to find an element with the text: Simplify. Go paperless. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible."

However the following test passes

{getByText} = render(<GuestGoPaperlessModal providerId={1} userPublicId="123"/>);
getByText("Simplify. Go paperless")

What's going on here? We are on version 12.1.5 of @testing-library/react

0

There are 0 best solutions below