Testing Reducers

Learn how to unit test the NgRx reducers.

Introduction

In the products module of our application, we have defined three actions. We handled those actions in the src/app/products/state/products.reducers.ts file with the productsReducer.

import { createAction, props } from "@ngrx/store";
import { Product } from "src/app/app.interfaces";
export const getProductsAction = createAction(
'[Products] Get Products',
props<{ products: Product[] }>()
)
export const loadProductsAction = createAction(
'[Products] Load Products'
)
export const getErrorAction = createAction(
'[Products] Load Products Error'
)
Actions defined in the products module

In this lesson, let’s write a test case to verify if our productsReducer is properly handling the getProductsAction().

Unit testing the NgRx reducers

We can unit test the NgRx reducers by following the steps below.

Creating a spec file

Inside the src/app/products/state folder, let’s create a new file named the products.reducers.spec.ts file. Angular will not run this test file unless we add the spec extension.

Snapshot of the folder structure of our project
Snapshot of the folder structure of our project

Defining the test suite

Let’s define a ...