Testing React with Enzyme, Jest and Fetch

I have been having fun recently working on a react app. Typically I use TDD.

This can be difficult when you have code that goes:

fetch.then(res => json)
.then(res => this.setState(res.aValue)

Testing this gets awkward. Changing the signature is too invasive. You can easily mock the fetch but get a race condition reading the state.

This is the solution that I found works. By abusing the javascript sequencing a bit – do what you need to then check this:

setTimeout(() => { assert thing.state}, 0)

2 thoughts on “Testing React with Enzyme, Jest and Fetch

  1. I came across a similar issue recently..
    I changed my async methods to return a promise. Then you can call that method and stick your assertions in the then block.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s