Writing Tests

Because most of the Redux code you write are functions, and many of them are pure, they are easy to test without mocking.

Setting Up

We recommend Jest as the testing engine.Note that it runs in a Node environment, so you won't have access to the DOM.

  1. npm install --save-dev jest

To use it together with Babel, you will need to install babel-jest:

  1. npm install --save-dev babel-jest

and configure it to use babel-preset-env features in .babelrc:

  1. {
  2. "presets": ["@babel/preset-env"]
  3. }

Then, add this to scripts in your package.json:

  1. {
  2. ...
  3. "scripts": {
  4. ...
  5. "test": "jest",
  6. "test:watch": "npm test -- --watch"
  7. },
  8. ...
  9. }

and run npm test to run it once, or npm run test:watch to test on every file change.

Action Creators

In Redux, action creators are functions which return plain objects. When testing action creators, we want to test whether the correct action creator was called and also whether the right action was returned.

Example

  1. export function addTodo(text) {
  2. return {
  3. type: 'ADD_TODO',
  4. text
  5. }
  6. }

can be tested like:

  1. import * as actions from '../../actions/TodoActions'
  2. import * as types from '../../constants/ActionTypes'
  3. describe('actions', () => {
  4. it('should create an action to add a todo', () => {
  5. const text = 'Finish docs'
  6. const expectedAction = {
  7. type: types.ADD_TODO,
  8. text
  9. }
  10. expect(actions.addTodo(text)).toEqual(expectedAction)
  11. })
  12. })

Async Action Creators

For async action creators using Redux Thunk or other middleware, it's best to completely mock the Redux store for tests. You can apply the middleware to a mock store using redux-mock-store. You can also use fetch-mock to mock the HTTP requests.

Example

  1. import 'cross-fetch/polyfill'
  2. function fetchTodosRequest() {
  3. return {
  4. type: FETCH_TODOS_REQUEST
  5. }
  6. }
  7. function fetchTodosSuccess(body) {
  8. return {
  9. type: FETCH_TODOS_SUCCESS,
  10. body
  11. }
  12. }
  13. function fetchTodosFailure(ex) {
  14. return {
  15. type: FETCH_TODOS_FAILURE,
  16. ex
  17. }
  18. }
  19. export function fetchTodos() {
  20. return dispatch => {
  21. dispatch(fetchTodosRequest())
  22. return fetch('http://example.com/todos')
  23. .then(res => res.json())
  24. .then(body => dispatch(fetchTodosSuccess(body)))
  25. .catch(ex => dispatch(fetchTodosFailure(ex)))
  26. }
  27. }

can be tested like:

  1. import configureMockStore from 'redux-mock-store'
  2. import thunk from 'redux-thunk'
  3. import * as actions from '../../actions/TodoActions'
  4. import * as types from '../../constants/ActionTypes'
  5. import fetchMock from 'fetch-mock'
  6. import expect from 'expect' // You can use any testing library
  7. const middlewares = [thunk]
  8. const mockStore = configureMockStore(middlewares)
  9. describe('async actions', () => {
  10. afterEach(() => {
  11. fetchMock.restore()
  12. })
  13. it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', () => {
  14. fetchMock.getOnce('/todos', {
  15. body: { todos: ['do something'] },
  16. headers: { 'content-type': 'application/json' }
  17. })
  18. const expectedActions = [
  19. { type: types.FETCH_TODOS_REQUEST },
  20. { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something'] } }
  21. ]
  22. const store = mockStore({ todos: [] })
  23. return store.dispatch(actions.fetchTodos()).then(() => {
  24. // return of async actions
  25. expect(store.getActions()).toEqual(expectedActions)
  26. })
  27. })
  28. })

Reducers

A reducer should return the new state after applying the action to the previous state, and that's the behavior tested below.

Example

  1. import { ADD_TODO } from '../constants/ActionTypes'
  2. const initialState = [
  3. {
  4. text: 'Use Redux',
  5. completed: false,
  6. id: 0
  7. }
  8. ]
  9. export default function todos(state = initialState, action) {
  10. switch (action.type) {
  11. case ADD_TODO:
  12. return [
  13. {
  14. id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
  15. completed: false,
  16. text: action.text
  17. },
  18. ...state
  19. ]
  20. default:
  21. return state
  22. }
  23. }

can be tested like:

  1. import reducer from '../../structuring-reducers/todos'
  2. import * as types from '../../constants/ActionTypes'
  3. describe('todos reducer', () => {
  4. it('should return the initial state', () => {
  5. expect(reducer(undefined, {})).toEqual([
  6. {
  7. text: 'Use Redux',
  8. completed: false,
  9. id: 0
  10. }
  11. ])
  12. })
  13. it('should handle ADD_TODO', () => {
  14. expect(
  15. reducer([], {
  16. type: types.ADD_TODO,
  17. text: 'Run the tests'
  18. })
  19. ).toEqual([
  20. {
  21. text: 'Run the tests',
  22. completed: false,
  23. id: 0
  24. }
  25. ])
  26. expect(
  27. reducer(
  28. [
  29. {
  30. text: 'Use Redux',
  31. completed: false,
  32. id: 0
  33. }
  34. ],
  35. {
  36. type: types.ADD_TODO,
  37. text: 'Run the tests'
  38. }
  39. )
  40. ).toEqual([
  41. {
  42. text: 'Run the tests',
  43. completed: false,
  44. id: 1
  45. },
  46. {
  47. text: 'Use Redux',
  48. completed: false,
  49. id: 0
  50. }
  51. ])
  52. })
  53. })

Components

A nice thing about React components is that they are usually small and only rely on their props. That makes them easy to test.

First, we will install Enzyme. Enzyme uses the React Test Utilities underneath, but is more convenient, readable, and powerful.

  1. npm install --save-dev enzyme

We will also need to install Enzyme adapter for our version of React. Enzyme has adapters that provide compatibility with React 16.x, React 15.x, React 0.14.x and React 0.13.x. If you are using React 16 you can run:

  1. npm install --save-dev enzyme-adapter-react-16

To test the components we make a setup() helper that passes the stubbed callbacks as props and renders the component with shallow rendering. This lets individual tests assert on whether the callbacks were called when expected.

Example

  1. import React, { Component } from 'react'
  2. import PropTypes from 'prop-types'
  3. import TodoTextInput from './TodoTextInput'
  4. class Header extends Component {
  5. handleSave(text) {
  6. if (text.length !== 0) {
  7. this.props.addTodo(text)
  8. }
  9. }
  10. render() {
  11. return (
  12. <header className="header">
  13. <h1>todos</h1>
  14. <TodoTextInput
  15. newTodo={true}
  16. onSave={this.handleSave.bind(this)}
  17. placeholder="What needs to be done?"
  18. />
  19. </header>
  20. )
  21. }
  22. }
  23. Header.propTypes = {
  24. addTodo: PropTypes.func.isRequired
  25. }
  26. export default Header

can be tested like:

  1. import React from 'react'
  2. import Enzyme, { shallow } from 'enzyme'
  3. import Adapter from 'enzyme-adapter-react-16'
  4. import Header from '../../components/Header'
  5. Enzyme.configure({ adapter: new Adapter() })
  6. function setup() {
  7. const props = {
  8. addTodo: jest.fn()
  9. }
  10. const enzymeWrapper = shallow(<Header {...props} />)
  11. return {
  12. props,
  13. enzymeWrapper
  14. }
  15. }
  16. describe('components', () => {
  17. describe('Header', () => {
  18. it('should render self and subcomponents', () => {
  19. const { enzymeWrapper } = setup()
  20. expect(enzymeWrapper.find('header').hasClass('header')).toBe(true)
  21. expect(enzymeWrapper.find('h1').text()).toBe('todos')
  22. const todoInputProps = enzymeWrapper.find('TodoTextInput').props()
  23. expect(todoInputProps.newTodo).toBe(true)
  24. expect(todoInputProps.placeholder).toEqual('What needs to be done?')
  25. })
  26. it('should call addTodo if length of text is greater than 0', () => {
  27. const { enzymeWrapper, props } = setup()
  28. const input = enzymeWrapper.find('TodoTextInput')
  29. input.props().onSave('')
  30. expect(props.addTodo.mock.calls.length).toBe(0)
  31. input.props().onSave('Use Redux')
  32. expect(props.addTodo.mock.calls.length).toBe(1)
  33. })
  34. })
  35. })

Connected Components

If you use a library like React Redux, you might be using higher-order components like connect(). This lets you inject Redux state into a regular React component.

Consider the following App component:

  1. import { connect } from 'react-redux'
  2. class App extends Component {
  3. /* ... */
  4. }
  5. export default connect(mapStateToProps)(App)

In a unit test, you would normally import the App component like this:

  1. import App from './App'

However, when you import it, you're actually holding the wrapper component returned by connect(), and not the App component itself. If you want to test its interaction with Redux, this is good news: you can wrap it in a <Provider> with a store created specifically for this unit test. But sometimes you want to test just the rendering of the component, without a Redux store.

In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component:

  1. import { connect } from 'react-redux'
  2. // Use named export for unconnected component (for tests)
  3. export class App extends Component {
  4. /* ... */
  5. }
  6. // Use default export for the connected component (for app)
  7. export default connect(mapStateToProps)(App)

Since the default export is still the decorated component, the import statement pictured above will work as before so you won't have to change your application code. However, you can now import the undecorated App components in your test file like this:

  1. // Note the curly braces: grab the named export instead of default export
  2. import { App } from './App'

And if you need both:

  1. import ConnectedApp, { App } from './App'

In the app itself, you would still import it normally:

  1. import App from './App'

You would only use the named export for tests.

A Note on Mixing ES6 Modules and CommonJS

If you are using ES6 in your application source, but write your tests in ES5, you should know that Babel handles the interchangeable use of ES6 import and CommonJS require through its interop capability to run two module formats side-by-side, but the behavior is slightly different. If you add a second export beside your default export, you can no longer import the default using require('./App'). Instead you have to use require('./App').default.

Middleware

Middleware functions wrap behavior of dispatch calls in Redux, so to test this modified behavior we need to mock the behavior of the dispatch call.

Example

First, we'll need a middleware function. This is similar to the real redux-thunk.

  1. const thunk = ({ dispatch, getState }) => next => action => {
  2. if (typeof action === 'function') {
  3. return action(dispatch, getState)
  4. }
  5. return next(action)
  6. }

We need to create a fake getState, dispatch, and next functions. We use jest.fn() to create stubs, but with other test frameworks you would likely use Sinon.

The invoke function runs our middleware in the same way Redux does.

  1. const create = () => {
  2. const store = {
  3. getState: jest.fn(() => ({})),
  4. dispatch: jest.fn()
  5. }
  6. const next = jest.fn()
  7. const invoke = action => thunk(store)(next)(action)
  8. return { store, next, invoke }
  9. }

We test that our middleware is calling the getState, dispatch, and next functions at the right time.

  1. it('passes through non-function action', () => {
  2. const { next, invoke } = create()
  3. const action = { type: 'TEST' }
  4. invoke(action)
  5. expect(next).toHaveBeenCalledWith(action)
  6. })
  7. it('calls the function', () => {
  8. const { invoke } = create()
  9. const fn = jest.fn()
  10. invoke(fn)
  11. expect(fn).toHaveBeenCalled()
  12. })
  13. it('passes dispatch and getState', () => {
  14. const { store, invoke } = create()
  15. invoke((dispatch, getState) => {
  16. dispatch('TEST DISPATCH')
  17. getState()
  18. })
  19. expect(store.dispatch).toHaveBeenCalledWith('TEST DISPATCH')
  20. expect(store.getState).toHaveBeenCalled()
  21. })

In some cases, you will need to modify the create function to use different mock implementations of getState and next.

Glossary

  • Enzyme: Enzyme is a JavaScript Testing utility for React that makes it easier to assert, manipulate, and traverse your React Components' output.

  • React Test Utils: Test Utilities for React. Used by Enzyme.

  • Shallow rendering: Shallow rendering lets you instantiate a component and effectively get the result of its render method just a single level deep instead of rendering components recursively to a DOM. Shallow rendering is useful for unit tests, where you test a particular component only, and importantly not its children. This also means that changing a child component won't affect the tests for the parent component. Testing a component and all its children can be accomplished with Enzyme's mount() method, aka full DOM rendering.