DEV Community

Discussion on: Understanding React Testing Library

Collapse
lukeshiru profile image
LUKESHIRU

My suggestion was mainly because the second example expects the component to have an internal loading state and we need to fire a load event which feels kinda weird. Ideally state should come from the parent in the form of props, and you can test for example if the component renders as expected when setting a loaded boolean property to false and if it renders the actual image when loaded is true. The way you'll use that would look something like this:

const [loaded, setLoaded] = useState(false);

return <Image src="example.png" loaded={loaded} onLoad={() => setLoaded(true)} />
Enter fullscreen mode Exit fullscreen mode

And then you can test it like this:

it('should render correctly while loading', async () => {
    const { asFragment } = render(<Image src="test.png" />);
    expect(asFragment()).toMatchSnapshot();
});

it('should render correctly when is loaded', async () => {
    const { asFragment } = render(<Image src="test.png" loaded />);
    expect(asFragment()).toMatchSnapshot();
});
Enter fullscreen mode Exit fullscreen mode

If you have your own mechanism to load the image and dispatch the onLoad event then you need to test that as well, but if you're using the browser's img element, you don't need to test it.

Don't get me wrong, the article is great, I just wanted to add to it by mentioning that ideally you shouldn't test stuff like internal state, or native behaviors, when you can just check if the output is the one you expect for different combinations of your custom props, and that the expected custom events are called.

Thread Thread
dhaiwat10 profile image
Dhaiwat Pandya Author

Thanks for the reply!

I think we are on different pages here. I don't have any loading state in my component like you mentioned. By default, Testing Library doesn't actually load your image. It doesn't fire the 'onLoad' event. (That's what we are doing with fireEvent.load(), not updating any internal state.) Which is why you can test if the image is correctly displaying a loader using the code I mentioned.

Thread Thread
dhaiwat10 profile image
Dhaiwat Pandya Author

And all of these events are native, none are custom. 😁

Thread Thread
lukeshiru profile image
LUKESHIRU

That's what I'm saying 😅 ... why would you test if the native img onLoad event works? Or if it changes something? If you do that, it seems like the component has a side effect when the image is done loading (which you'll emulate from RTL with fireEvent.load). Ideally the component shouldn't do that by itself, but actually receive it from the parent (which is easier to test, because you don't need that fireEvent at all).