Testing React components

Wisdom from writing countless UI tests and a new API for component testing

Photo by Jason Wong

№1 component=f(props, state) is a lie

component=f(props, state, context)
component=f(props, state, Redux, Router, Theme, Intl, etc)
component=f(props, state, context, globals)
component=f(props, state, context, fetch, localStorage, window size)

Testing React components is a constant challenge, but very few talk about The Struggle. Official testing examples feature basic components, but taming the Monster Components is mostly taboo. Together we’ll look the beast in the eye and talk about a simple (new) testing API that puts any component to sleep and nicely complements existing tooling like Jest & Enzyme.

Could not find “store” in either the context or props of Connect…ReferenceError: fetch is not definedReferenceError: localStorage is not defined

№2 Beware of the “glue” between your units

OK, but the test setup is overwhelming…

If only there was an easy way to simulate component states by mocking inputs…

Cosmos Playground

What’s a fixture?

<Button disabled={true}>Click me maybe</Button>

Now, imagine a fixture as a React element on steroids…

props: {}
url: '/dashboard',

localStorage: {
name: 'Dan'

reduxState: {},

fetch: [
matcher: '/api/login',
response: {
name: 'Dan'
Fun fact: The Cosmos UI is tested using the Cosmos Testing API

Slow thinker. INFJ. Fluent in JavaScript. Love to learn by creating. Evergreen newbie. https://ovidiu.ch

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store