When using Ngrx, we need to know how to test the component which has Router injected.
Component:
import {Component} from '@angular/core'; import {FormGroup} from '@angular/forms'; import {Store} from '@ngrx/store'; import * as fromAuth from '../../reducers/auth'; import * as actions from '../../actions/auth'; @Component({ selector: 'register', templateUrl: './register.component.html', styleUrls: ['./register.component.scss'] }) export class RegisterComponent { error: string; constructor(private store: Store<fromAuth.State>) { } registerUser(event: FormGroup) { const {email, password} = event.value; this.store.dispatch(new actions.Register({ email, password })); } }
One thing we can test just for component wihtout template is to test whether 'dispatch' function was called on Store.
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {RegisterComponent} from './register.component'; import {RouterTestingModule} from '@angular/router/testing'; import {combineReducers, Store, StoreModule} from '@ngrx/store'; import {SharedModule} from '../../shared/SharedModule'; import {State as AuthState, reducers as AuthReducers} from '../../reducers'; import {Register, REGISTER} from '../../actions/auth'; import * as fromRoot from '../../../reducers'; import {FormGroup} from '@angular/forms'; describe('RegisterComponent', () => { let component: RegisterComponent; let fixture: ComponentFixture<RegisterComponent>; let store: Store<fromRoot.State | AuthState>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [RegisterComponent], imports: [ StoreModule.forRoot({ ...fromRoot.reducers, 'auth': combineReducers(AuthReducers) }), SharedModule ] }) .compileComponents(); })); beforeEach(() => { store = TestBed.get(Store); spyOn(store, 'dispatch').and.callThrough(); fixture = TestBed.createComponent(RegisterComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should call distach when rigster a new user', () => { const payload = { email: 'test@test.com', password: 'test123' }; const event = { value: payload }; const action = new Register(payload); // init the action creatir component.registerUser(event as FormGroup); // call the function or trigger from DOM expect(store.dispatch).toHaveBeenCalledWith(action); // expect the dispatch have been call expect(action.payload).toBe(payload); // check whether payload is correct expect(action.type).toBe(REGISTER); // check the action type is correct }); });