📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • Testing Action Creators
  • Testing Reducers
  • When to Unit Test Action Creators and Reducers
  • Testing Redux Connected Components
  • Enzyme dive method
  • Tradeoffs when testing redux
  1. Javascript
  2. React Testing

Redux Testing

In this section, we'll learn how to test

  • Action creators

  • Reducers

  • Thunks

  • Asynchronous action creators

  • State and action creators in connected component props

Testing Action Creators

Action creators are really easy to test because they're just vanilla JS. You basically just use toEqual to check for deep equality of the action object returned:

// actions.js
const setUsername = username => ({
  type: 'SET_USERNAME',
  username
})

// actions.test.js
test('setUsername returns action object with username as property', () => {
  const username = 'danfitz'
  const action = setUsername(username)

  expect(action).toEqual({
    type: 'SET_USERNAME',
    username
  })
})

Testing Reducers

Reducers are vanilla JS just like action creators, so the process is the same:

// reducer.js
const initialState = false
const reducer = (state=initialState, action) => {
  switch (action.type) {
    case "SET_TRUE":
      return true
    default:
      return state
  }
}

// reducer.test.js
test('returns default state of `false` when no action passed', () => {
  const newState = reducer(initialState, {})
  expect(newState).toBe(false)
})

test('returns state of `false` when SET_TRUE action passed', () => {
  const newState = reducer(initialState, { type: 'MAKE_TRUE' })
  expect(newState).toBe(true)
})

When to Unit Test Action Creators and Reducers

Some developers think that unit testing action creators and reducers is unnecessary. Instead, you only need to perform integration tests on the API, i.e., simulating user interaction and seeing how it affects the redux store. In this case, action creators and reducers are treated as implementation details, and all that matters is the end result for the user.

The benefit of this approach is fewer tests to maintain and refactor when code is refactored. The disadvantage is that sometimes it will be harder to pinpoint what exactly went wrong if you don't have fine-grained unit tests.

Rule of thumb: At the very least, it's a good idea to unit test your action creators and reducers when they become sufficiently complicated. Dead simple ones may not be worth your time.

Testing Redux Connected Components

When testing components that access redux store via the connect higher-order wrapper, you don't automatically have access to store. That's because there's no parent Provider to provide the context.

The solution to this is to

  1. Create a storeFactory helper function that mirrors your configuration of store in your store.js file, and then

  2. Pass store as a prop to the component you're testing.

Note: Passing store as a prop works because of jest (?).

import { createStore } from 'redux'
import rootReducer from './reducers'

const storeFactory = initialState => {
  return createStore(rootReducer, initialState)
}

// In test file, you can now include `store` in your `setup` helper
const setup = (initialState={}) => {
  const store = storeFactory(initialState)
  const wrapper = shallow(<Component store={store} />)
  return wrapper
}

Now when you test your component, you should be able to test redux state.

Enzyme dive method

When you provide a redux store in your tests, your component gets passed through a higher-order component, getting wrapped around a Provider.

Since shallow only renders the outermost component and none of its children, you need to dive in order to reach the DOM nodes you care about.

// What you get from shallow()
<ContextProvider>
  <Component />
</ContextProvider>

// What you want: contents of component
<h1>Hello!</h1>

// How to reach it: dive twice
// Once to get to child component and a second time for contents of child component
const wrapper = shallow(<Component store={store} />).dive().dive()

Pro tip: An alternative to the dive approach is to just export the unconnected component and test that.

Tradeoffs when testing redux

Do you want to test the actual store or a mock store? You can use a library called redux-mock-store, which allows you to test intermediate actions that lead up to your final state. Whereas using the actual store only allows you to test the final state. On the other hand, the actual store is closer to the live app. This is tradeoff you want to think about.

Do you want to test connected or unconnected components? Connected components are closer to the live app,and they allow you to test the store state. On the other hand, unconnected components allow you to pass action creators as props. (Why does that matter?) Again, this is a tradeoff decision.

PreviousBasic TestingNextRedux Thunk Testing

Last updated 3 years ago