Subscribe

Testing library asFragment tests

โœ๏ธ

Using asFragment in Testing Library to find initial renders

18 Apr, 2022 ยท 2 min read

Sometimes we might have tests that change over time or specific user actions.

We might use a timeout to change some text or even wait for a click action to show the user something different.

Letโ€™s take the following example as our use-case:

function App() {
  const [text, setText] = useState('Wait a second');
  useEffect(() => {
    setTimeout(() => {
      setText('All done');
    }, 200);
  }, []);
  return text;
}

This app will show Wait a second until 200ms are passed and then show All done.

So how can we test if this is working?

Using testing library asFragment tests

This could be an excellent option for the asFragment API.

We can leverage the asFragment API to take a Document Fragment of the component in the first render.

It would look something like this:

const { asFragment } = render(<App />);
const firstRender = asFragment();

We then want to wait for the text to change, so letโ€™s query for the specific text.

expect(await screen.findByText('All done')).toBeInTheDocument();

The test will wait for the text to become visible. So how can we now make sure the first render has a different text?

expect(firstRender).toMatchSnapshot();

It will now write a snapshot that has:

<DocumentFragment> Wait a second </DocumentFragment>

Which is perfect. You can also include an external plugin to find the differences between the two snapshots: snapshot-diff.

Conclusion

There are cases where itโ€™s super handy to have a fragment of the initial render to find changes from the initial render.

Iโ€™d love to hear your use-cases for the asFragment API as well.

Thank you for reading, and letโ€™s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

Changing the default testing container

17 Apr, 2022 ยท 3 min read

Changing the default testing container

Testing library and React context

16 Apr, 2022 ยท 4 min read

Testing library and React context

Join 2099 devs and subscribe to my newsletter