Stats

1024 Contributors: 5 Tuesday, August 1, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Mocking @ngrx/Store

Introduction

@ngrx/Store is becoming more widely used in Angular 2 projects. As such, the Store is required to be injected into the constructor of any Component or Service that wishes to use it. Unit testing Store isn't as easy as testing a simple service though. As with many problems, there are a myriad of ways to implement solutions. However, the basic recipe is to write a mock class for the Observer interface and to write a mock class for Store. Then you can inject Store as a provider in your TestBed.

Parameters

namedescription
valuenext value to be observed
errordescription
errerror to be thrown
superdescription
action$mock Observer that does nothing unless defined to do so in the mock class
actionReducer$mock Observer that does nothing unless defined to do so in the mock class
obs$mock Observable

Remarks

Observer is a generic, but must be of type any to avoid unit testing complexity. The reason for this complexity, is that Store's constructor expects Observer arguments with different generic types. Using any avoids this complication.

It's possible to pass null values into StoreMock's super constructor, but this restricts the number of assertions that can be used to test the class further down the road.

The Component being used in this example is just being used as context for how one would go about injecting Store as a provide in the test setup.

Related Examples