17.10.2018 Views

Angular

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 39: Mocking @ngrx/Store<br />

name<br />

value<br />

error<br />

err<br />

super<br />

next value to be observed<br />

description<br />

error to be thrown<br />

description<br />

description<br />

action$<br />

mock Observer that does nothing unless defined to do so in the mock class<br />

actionReducer$ mock Observer that does nothing unless defined to do so in the mock class<br />

obs$<br />

mock Observable<br />

@ngrx/Store is becoming more widely used in <strong>Angular</strong> 2 projects. As such, the Store is required to be injected into<br />

the constructor of any Component or Service that wishes to use it. Unit testing Store isn't as easy as testing a simple<br />

service though. As with many problems, there are a myriad of ways to implement solutions. However, the basic<br />

recipe is to write a mock class for the Observer interface and to write a mock class for Store. Then you can inject<br />

Store as a provider in your TestBed.<br />

Section 39.1: Unit Test For Component With Mock Store<br />

This is a unit test of a component that has Store as a dependency. Here, we are creating a new class called<br />

MockStore that is injected into our component instead of the usual Store.<br />

import { Injectable } from '@angular/core';<br />

import { TestBed, async} from '@angular/core/testing';<br />

import { AppComponent } from './app.component';<br />

import {DumbComponentComponent} from "./dumb-component/dumb-component.component";<br />

import {SmartComponentComponent} from "./smart-component/smart-component.component";<br />

import {mainReducer} from "./state-management/reducers/main-reducer";<br />

import { StoreModule } from "@ngrx/store";<br />

import { Store } from "@ngrx/store";<br />

import {Observable} from "rxjs";<br />

class MockStore {<br />

public dispatch(obj) {<br />

console.log('dispatching from the mock store!')<br />

}<br />

public select(obj) {<br />

console.log('selecting from the mock store!');<br />

}<br />

}<br />

return Observable.of({})<br />

describe('AppComponent', () => {<br />

beforeEach(() => {<br />

TestBed.configureTestingModule({<br />

declarations: [<br />

AppComponent,<br />

SmartComponentComponent,<br />

DumbComponentComponent,<br />

],<br />

imports: [<br />

StoreModule.provideStore({mainReducer})<br />

],<br />

GoalKicker.com – <strong>Angular</strong> 2 Notes for Professionals 137

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!