4

🌶️ Hot tip - Use snapshots in React Testing Library to debug faster ⚙️

 1 year ago
source link: https://dev.to/jozsefdevs/hot-tip-use-snapshots-in-react-testing-library-to-debug-faster-42o7
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
jozsefDevs

Posted on Jan 23

🌶️ Hot tip - Use snapshots in React Testing Library to debug faster ⚙️

So you have this test that is already spitting out something big and complex to DOM and it's failing to find the expected element. You see the usual error message TestingLibraryElementError: Unable to find an element with the text: ... and absolutely have no idea where things might have gone wrong. Inline errors are nice, however, you can't see the problem. 🙈

Usual error message for failing test

🍀 To solve this we will leverage snapshot testing! 🍀

Modify your test to get the container out of render, then make a snapshot with expect(container).toMatchSnapshot() 🪄. Notice, this trick can be applied regardless of the complexity of your test.

Create a snapshot file to better understand your DOM

Re-run your test you'll see the snapshot file 🎉 (App.test.tsx.snap), which is now totally under your control.

You can easily spot the problem and search your way through. It's pretty printed and already formatted as your IDE knows this stuff. Feel free to look around and close/open tags to see what is the actual DOM content at this point of the test.

Navigable snapshot of your DOM

Okay, we've found the problem, we missed some additional characters inside. Now we can fix our test. We can rerun and see it's all green 💚.

Test fixed

🚨 Also, make sure you remove the *.snap file and the related toMatchSnapshot line to avoid having unexpected snapshot tests later.

💡 This technique is especially useful when your component is rendering a huge markup (maybe a composite component already) and you can't find out why your test is not finding an element.

💡 Also useful to apply this technique if you just want to know the DOM state at a given step. If you are testing a loader with async data, you'll be able to make a snapshot before and after the async data have been loaded.

Let me know if you find this useful 😊

Hungry for more RTL tips 🍽️ ? See my previous post ➡️ Top 3 React Testing Library mistakes I should have spotted earlier 🚀

Happy testing!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK