Unit Testing

React + Redux Applications

Nikhil John

Unit Testing

!=

Component Testing

!=

Integration Testing

!=

Visual Regression Testing

Unit Testing

Is testing smallest parts i.e. Reducers, Sagas, Components, Containers

Unit Testing

Is not testing API interaction or functional flows

How to write unit tests

  • Sprinkle .test.js files directly next to the parts of your application you want to test. (Or in test/ subdirectories, it doesn't really matter as long as they are directly next to those parts and end in .test.js)
  • Write your unit tests in those files.

  • npm run test:watch
    OR
    
  • npm run test

Our Unit testing setup

  • Jest test framework runs tests and make assertions.
  • Writing tests ~ speaking - you describe a unit of your code and expect it to do the correct thing

Example

// add.js

export function add(x, y) {
  return x + y;
}

// add.test.js
import { add } from '../add';
describe ('add()', () => {
  it('adds two numbers', () => {
    expect(add(1, 2)).toEqual(5);
  });
  it('doesn't add subsequent args after second', () => { 
    expect(add(1, 2, 3)).toEqual(add(1,2));
  });
})

 

Should our function work, Jest will show this output when running the tests:

add()
  ✓ adds two numbers
  ✓ ​doesn't add subsequent args after second

What if add.js changes?

// add.js

export function add(x, y) {
  return x * y;
}

add() › adds two numbers

  expect(received).toEqual(expected)

  Expected value to equal:
    5
  Received:
    6

add()
  ✕ adds two numbers
  ✓ doesn't add the third number

Testing Reducers

  • Reducers are (well, should be) pure functions
  • InitialState + Action = NewState

Testing Actions

  • Actions are simple objects created by Action Creators
  • Expect a simple JS object
  • No side effects inside actions

Testing Sagas

  • redux-sagas are built to be testable
  • More here

Unit TestingReact + Redux Applications

By Nikhil John

Unit TestingReact + Redux Applications

  • 608