typescript 模拟NGRX商店。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 模拟NGRX商店。相关的知识,希望对你有一定的参考价值。

import { Action, Store } from '@ngrx/store';
import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


/**
 * Standard mockstore that can be used in unittests to mock a @ngrx/store
 *
 * https://github.com/ngrx/store/issues/128#issuecomment-316654714
 */
export class MockStore<T> {
  reducers = new Map<string, BehaviorSubject<any>>();

  /**
   * Simple solution to support selecting/subscribing to this mockstore as usual.
   *
   * @param name - Reducer name
   * @returns {undefined|BehaviorSubject<any>}
   */
  select(name) {
    if (!this.reducers.has(name)) {
      this.reducers.set(name, new BehaviorSubject({}));
    }
    return this.reducers.get(name);
  }

  /**
   * Used to set a fake state
   *
   * @param reducerName - The name of your reducer
   * @param data - The mock data
   */
  mockState(reducerName, data) {
    this.select(reducerName).next(data);
  }

  dispatch(data: any) {
    // ...
  }
}
export interface UserArgs {
  id: number;
  firstName: string;
  lastName: string;
}
export class User {
  public firstName: string;
  public lastName: string;
  public id: number;

  constructor({firstName, lastName, id}: UserArgs) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }

  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const userMock = new User({firstName: 'foo', lastName: 'bar', id: 10});


describe(`getStateValue`, () => {
  let storeMock;

  beforeEach(() => {
    storeMock = new MockStore();
    storeMock.mockState('users', [userMock]);
  });


  test(`should return the value of the store`, () => {
    storeMock.select('users').subscribe((v) => {
      expect(v).toEqual([userMock]);
    })
  });

});

以上是关于typescript 模拟NGRX商店。的主要内容,如果未能解决你的问题,请参考以下文章

typescript @ ngrx /商店柜台

typescript @ ngrx /商店柜台

在单元测试中使用参数模拟 ngrx 存储选择器(Angular)

使用 @ngrx/entity 处理商店中的集合,getSelectors() 不起作用

错误:商店没有提供者!在@ngrx 4.x

NgRx 无法从商店中选择