This is the child article of ReactTestUtils - Tutorial. In this article, I will explain how to write test cases for React-Redux apps.

Redux apps maintains common state for all components, so one component state might be depend on action in other component. So you should better test whole application with Provider and Store than testing each and every component.

Example

Lets take a Todo example.  You can find source of this example here

Testing Flow

  1. Enter test 'Sample task' in input field
  2. Click enter
  3. Check Todo Item is added or not
  4. Click on check box of that Todo Item
  5. Check whether todo task is completed or not

Setup 

Create store using reducers. Render the App component with Provider and store. This is basic setup to test Redux applications.
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import expect from 'expect';
import reducer from '../reducers'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import App from '../containers/App'

const store = createStore(reducer)

describe('root', function () {

  it('renders without problems', function () {
    var root = TestUtils.renderIntoDocument(<Provider store={store}>
      <App />
    </Provider>);
    expect(root).toExist();
  });

});

Test Flow

The above described test flow can be found below. 
it('Todo lifecycle test', function () {
    var root = TestUtils.renderIntoDocument(<Provider store={store}>
      <App/>
    </Provider>);
    var compArr = TestUtils.findRenderedComponentWithType(root, TodoTextInput);

    // change input text value
    var inputElm = TestUtils.findRenderedDOMComponentWithTag(compArr, 'input');
    inputElm.value = 'some task';
    TestUtils.Simulate.change(inputElm);

    // press enter
    TestUtils.Simulate.keyDown(inputElm, {which : 13});

    // find ToDo Items and verify the value
    var todoItems = TestUtils.scryRenderedComponentsWithType(root, TodoItem);
    expect(todoItems[0].props.todo.text).toEqual('some task');

    // check the todo item
    var checkbox = TestUtils.findRenderedDOMComponentWithTag(todoItems[0], 'input');
    checkbox.checked = true;
    TestUtils.Simulate.change(checkbox);

    // check todo completion
    expect(todoItems[0].props.todo.completed).toEqual(true);
});

0 comments:

Blogroll

Follow this blog by Email

Popular Posts