

🌶️ Hot tip - Use snapshots in React Testing Library to debug faster ⚙️
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.

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. 🙈
🍀 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.
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.
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 💚.
🚨 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!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK