[Angular & Unit Testing] Testing Component with Store

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
  });
});
复制代码

 

posted @   Zhentiw  阅读(565)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-10-10 [Ramda] Getter and Setter in Ramda & lens
2016-10-10 [Angular2 Router] Index router
2016-10-10 [TypeScript] Using Interfaces to Describe Types in TypeScript
2016-10-10 [RxJS] ReplaySubject with buffer
2016-10-10 [Ramda] Declaratively Map Predicates to Object Properties Using Ramda where
2016-10-10 [Ramda] Pluck & Props: Get the prop(s) from object array
2016-10-10 [Ramda] Complement: Logic opposite function
点击右上角即可分享
微信分享提示