Skip to content
Advertisement

How to test snapshots with Jest and new React lazy 16.6 API

I have to components imported with the new React lazy API (16.6).

JavaScript

In my tests, I’m doing the snapshots of this component. It’s a very straightforward test:

JavaScript

In the logs, the test is failing with this error:

JavaScript

Do I have to wrap in every single test suite with <Suspense>...?

JavaScript

If I do that, I only see in the snapshot the fallback component.

JavaScript

So, which is the best way to do it?

Advertisement

Answer

Do I have to wrap in every single test suite with <Suspense>?

Yes, the Suspense component is neccessary for lazily loading child components, particularly providing a fallback and for reconciliation when the lazy components are available.

Export Component1 and Component2 in CustomComponent so that they can be imported in tests.

JavaScript

Remember that the lazy loaded components are promise-like. Import them in the test, and wait for them to resolve before doing a check that the snapshot matches.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement