Let’s take an example React component,
Let’s write a test for it using Jest and Enzyme,
Some points to note here are:
- By passing the
donefunction here, we’re telling Jest to wait until the
donecallback is called before finishing the test. See Testing Asynchronous Code docs for more details.
- Since we
awaitthe call to
Promise.resolveit in the test to a
- Since we are
awaiting the call to
ExampleComponent.js, and expecting the returned object to contain a
jsonfunction, which returns another
Promise.resolveto an object containing such a
- We spy on
window.fetchand mock it’s implementation to return the
Promiseobject described in 3.
- We invoke Enzyme to shallow render, which also invokes the React lifecycle methods *.
- Wrapping our assertion code inside a
process.nextTick()ensures that the functions queued in the current event loop are completed, thus also ensuring that our
Promises and other code inside
ExampleComponentis done executing.
- Optionally, we clear the mock.
- We invoke
doneto tell Jest that this test case is complete.