When using Ngrx, we need to know how to test the component which has Router injected.

Component:

  1. import {Component} from '@angular/core';
  2. import {FormGroup} from '@angular/forms';
  3. import {Store} from '@ngrx/store';
  4.  
  5. import * as fromAuth from '../../reducers/auth';
  6. import * as actions from '../../actions/auth';
  7.  
  8. @Component({
  9. selector: 'register',
  10. templateUrl: './register.component.html',
  11. styleUrls: ['./register.component.scss']
  12. })
  13. export class RegisterComponent {
  14.  
  15. error: string;
  16.  
  17. constructor(private store: Store<fromAuth.State>) {
  18.  
  19. }
  20.  
  21. registerUser(event: FormGroup) {
  22. const {email, password} = event.value;
  23. this.store.dispatch(new actions.Register({
  24. email,
  25. password
  26. }));
  27. }
  28.  
  29. }

One thing we can test just for component wihtout template is to test whether 'dispatch' function was called on Store.

  1. import {async, ComponentFixture, TestBed} from '@angular/core/testing';
  2.  
  3. import {RegisterComponent} from './register.component';
  4. import {RouterTestingModule} from '@angular/router/testing';
  5. import {combineReducers, Store, StoreModule} from '@ngrx/store';
  6. import {SharedModule} from '../../shared/SharedModule';
  7.  
  8. import {State as AuthState, reducers as AuthReducers} from '../../reducers';
  9. import {Register, REGISTER} from '../../actions/auth';
  10. import * as fromRoot from '../../../reducers';
  11. import {FormGroup} from '@angular/forms';
  12.  
  13. describe('RegisterComponent', () => {
  14. let component: RegisterComponent;
  15. let fixture: ComponentFixture<RegisterComponent>;
  16. let store: Store<fromRoot.State | AuthState>;
  17.  
  18. beforeEach(async(() => {
  19. TestBed.configureTestingModule({
  20. declarations: [RegisterComponent],
  21. imports: [
  22. StoreModule.forRoot({
  23. ...fromRoot.reducers,
  24. 'auth': combineReducers(AuthReducers)
  25. }),
  26. SharedModule
  27. ]
  28. })
  29. .compileComponents();
  30. }));
  31.  
  32. beforeEach(() => {
  33.  
  34. store = TestBed.get(Store);
  35. spyOn(store, 'dispatch').and.callThrough();
  36.  
  37. fixture = TestBed.createComponent(RegisterComponent);
  38. component = fixture.componentInstance;
  39. fixture.detectChanges();
  40. });
  41.  
  42. it('should create', () => {
  43. expect(component).toBeTruthy();
  44. });
  45.  
  46. it('should call distach when rigster a new user', () => {
  47. const payload = {
  48. email: 'test@test.com',
  49. password: 'test123'
  50. };
  51. const event = {
  52. value: payload
  53. };
  54. const action = new Register(payload); // init the action creatir
  55. component.registerUser(event as FormGroup); // call the function or trigger from DOM
  56. expect(store.dispatch).toHaveBeenCalledWith(action); // expect the dispatch have been call
  57. expect(action.payload).toBe(payload); // check whether payload is correct
  58. expect(action.type).toBe(REGISTER); // check the action type is correct
  59. });
  60. });

[Angular & Unit Testing] Testing Component with Store的更多相关文章

  1. [Angular & Unit Testing] Testing a RouterOutlet component

    The way to test router componet needs a little bit setup, first we need to create a "router-stu ...

  2. [Angular + Unit Testing] Mock HTTP Requests made with Angular’s HttpClient in Unit Tests

    In a proper unit test we want to isolate external dependencies as much as possible to guarantee a re ...

  3. [Angular Unit Testing] Debug unit testing -- component rendering

    If sometime you want to log out the comonent html to see whether the html render correctly, you can ...

  4. [Angular Unit Testing] Testing Component methods

    import {ComponentFixture, TestBed} from '@angular/core/testing'; import {BrowserDynamicTestingModule ...

  5. [Angular Testing] Unit Testing -- Test component and service.

    Recommend to use angular-cli to generate component and service, so we can get testing templates. ng ...

  6. [Angular & Unit Testing] Automatic change detection

    When you testing Component rendering, you often needs to call: fixture.detectChanges(); For example: ...

  7. [Angular Unit Testing] Shallow Pipe Testing

    import { TestBed, ComponentFixture } from '@angular/core/testing'; import { BrowserDynamicTestingMod ...

  8. [Angular Unit Testing] Testing Services with dependencies

    import { Http, Response, ResponseOptions } from '@angular/http'; import { TestBed } from '@angular/c ...

  9. [Angular + Unit] AngularJS Unit testing using Karma

    http://social.technet.microsoft.com/wiki/contents/articles/32300.angularjs-unit-testing-using-karma- ...

随机推荐

  1. 【J-meter】正则表达式提取

    当获取的值中含有折行,可采用下面的办法解决:

  2. 关于git及其github的使用

    一:序言(就是瞎扯) 人们都说不会使用git和github的程序员都不是好程序员,是的,当我第一次听到的时候有点失望.因为我也不会...但是这句话激起了我学习使用git的动力(其实也没怎么深入的学习) ...

  3. [React] Pass a function to setState in React

    In React, when you want to set the state which calculation depends on the current state, using an ob ...

  4. 关于HttpClient模拟浏览器请求的參数乱码问题解决方式

    转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/44407297 http://www.llwjy.com/blogdetail/9 ...

  5. FSM的几种策略

    FSM是什么?FSM就是Finite(有限) State(状态) 机(Machine)的缩写.(之所以中英文混写,是为了强调学懂FSM的原理是根本,刻意去采用“几段式”的写法并不重要) riple F ...

  6. 在spring-mybatis.xml 中配置pagehelper

    maven导包:<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</ ...

  7. POJ - 3847 Moving to Nuremberg 动归

    POJ - 3847 Moving to Nuremberg 题意:一张无向有权图,包括边权和点权,求一点,使得到其他点的点权*边权之和最小 思路: #pragma comment(linker, & ...

  8. POJ 1610 Count the Colors

    Count the Colors Time Limit: 2 Seconds      Memory Limit: 65536 KB Painting some colored segments on ...

  9. asp.net 关于cookie的操作

    一.无子键或单级cookie 读写(1).写入: 第一种 HttpCookie cookie=new HttpCookie("User"); cookie.Value=" ...

  10. 【MySQL主从复制原理及搭建全过程】

    目录 准备工作 主从复制原理 开始搭建主从复制 本文将使用mariaDB数据库实现主从复制,其步骤与MySQL数据库无差异. MariaDB数据库管理系统是MySQL的一个分支,主要由开源社区在维护, ...