Testing Effects: Configuring the TestBed
Learn how to configure the TestBed to test the NgRx effects.
Introduction
NgRx Effects are a little more tricky to unit test than reducers and selectors. Therefore, this kind of unit testing will be covered in three lessons.
In this lesson, we’ll configure the TestBed
so that it can test the ProductsEffects
defined in the Products
module.
import { Injectable } from "@angular/core";import { Actions, createEffect, ofType } from "@ngrx/effects";import { catchError, map, mergeMap, of } from "rxjs";import { Product } from "src/app/app.interfaces";import { ProductsService } from "src/app/products.service";import { loadProductsAction, getProductsAction, getErrorAction } from "./products.actions";@Injectable()export class ProductsEffects {constructor(private actions$: Actions,private productsService: ProductsService) { }loadProducts$ = createEffect(() => {return this.actions$.pipe(ofType(loadProductsAction),mergeMap(action => this.productsService.getProducts().pipe(map((products: Product[]) => getProductsAction({ products })),catchError(() => of(getErrorAction())))))})}
What is a TestBed
?
When we develop a new feature in an Angular application, we usually start with a new NgModule
. Then, within that module, we create components, inject services, directives, pipes, and so on.
We need to set up this entire process while unit testing. Instead of setting up this process manually, Angular provides us with the TestBed
. The TestBed
creates an Angular environment through which we can easily test various parts of our application.
Configuring the TestBed
Let’s configure our TestBed
to unit test the ProductsEffects
by following the steps below.
Creating a spec
file
Inside the src/app/products/state
folder, let’s create a new file named products.effects.spec.ts
.
Defining the test suite
Let’s define a test suite by using the describe
function.
describe('ProductsEffects: loadProducts$', () => {});