From 5cb9a4669fc69c0a3f2789f49fcf9942f7549225 Mon Sep 17 00:00:00 2001 From: Suguru Inatomi Date: Sat, 2 Mar 2019 00:07:34 +0900 Subject: [PATCH] docs(store): add section for provideMockStore to testing guide (#1591) --- .../ngrx.io/content/guide/store/testing.md | 61 ++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/projects/ngrx.io/content/guide/store/testing.md b/projects/ngrx.io/content/guide/store/testing.md index 71d37a99bc..13e24f3f9c 100644 --- a/projects/ngrx.io/content/guide/store/testing.md +++ b/projects/ngrx.io/content/guide/store/testing.md @@ -1,6 +1,65 @@ # Testing -### Providing Store for testing +### Using a Mock Store + +The `provideMockStore()` function registers providers that allow you to mock out the `Store` for testing functionality that has a dependency on `Store` without setting up reducers. +You can write tests validating behaviors corresponding to the specific state snapshot easily. + +
+ +**Note:** All dispatched actions don't affect to the state, but you can see them in the `Actions` stream. + +
+ +Usage: + + +import { TestBed } from '@angular/core/testing'; +import { Store } from '@ngrx/store'; +import { provideMockStore } from '@ngrx/store/testing'; +import { cold } from 'jasmine-marbles'; + +import { AuthGuard } from '../guards/auth.guard'; +import * as AuthActions from '../actions/auth-actions'; + +describe('Auth Guard', () => { + let guard: AuthGuard; + let store: MockStore<{ loggedIn: boolean }>; + const initialState = { loggedIn: false }; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + // any modules needed + ], + providers: [ + AuthGuard, + provideMockStore({ initialState }), + // other providers + ], + }); + + guard = TestBed.get(AuthGuard); + store = TestBed.get(Store); + }); + + it('should return false if the user state is not logged in', () => { + const expected = cold('(a|)', { a: false }); + + expect(guard.canActivate()).toBeObservable(expected); + }); + + it('should return true if the user state is logged in', () => { + store.setState({ loggedIn: true }); + + const expected = cold('(a|)', { a: true }); + + expect(guard.canActivate()).toBeObservable(expected); + }); +}); + + +### Using Store for Integration Testing Use the `StoreModule.forRoot` in your `TestBed` configuration when testing components or services that inject `Store`.