Pro Tip: Use Async / Await With Act To Avoid Act Warnings in Jest / Enzyme Tests And Have Components Update Properly!
I was having a hard time recently writing jest + enzyme unit tests for a react.js project, and one of my colleagues saved the day with the await / async addition. In this post I'll go through what I was doing, what I tried that didn't work, and what we ultimately went with that fixed everything!
Consider this code below. It may seem to you like a perfectly logical test that uses Enzyme to "mount" a CancelTaskComponent. The cancel component isn't just a single cancel button... come on guys, that's not cool! No, this cancel component has a cancel button that, when pressed, reveals a textarea for the user to provide a "cancellation reason", and a final submit button. After clicking the final submit button we expect our "datafetcher" service to call the backend with out cancellation reason and the cancellation textarea to be cleared out. Take a gander:
Interestingly, this code passes when I run it with Jest, but I get these gross red errors in my console even though the test was passing! Gad zooks, my dear!
After seeing this error, I went through my code and trie many combinations of things wrapped in this call to "act" which takes a anonymous function inside of which you put your "state updating code". unfortunately, this did not solve my issue. I tried to wrap the entire contents of my "it" block, but then why I ran the assertions it seemed that my components were not updating. AAaaarrrrgggh!! Wht can I do?
I forget how we originally figured this out, but a consistent way we found to relieve ourselves of this warning was to wrap our "state updating code" in these async / await versions of act. See the updated code below:
This above code is working nicely for me, updating the components correctly, and most importantly not throwing any nasty red act warnings!
Let me know how it works for you!
The posts on this site are written and maintained by Jim Lynch. About Jim...
Want FREE access to
my daily stock tips
"The Triple Gainers"?
Sign up here!