【问题标题】:Unit testing Angular component + ngrx store单元测试 Angular 组件 + ngrx 存储
【发布时间】:2019-02-18 20:38:15
【问题描述】:

尝试测试我的角度组件。

我有根状态和模块状态,看起来像:

state {
  auth: {
  // user data
  },
  messagesModule:{
   // here's module state
    messages:[...]
  }
}

初始消息状态为空对象。

组件:

export class MessagesComponent {
  public messages$: Observable<number>;

  constructor(private store: Store<any>) {
   this.messagesLengh$ = store.pipe(select('getMessagesLengh'));
  }
...

选择器

export const msgLength = (state: AppState) => state.messages.lenght;

测试

describe('MessagesComponent', () => {
  let component: MessagesComponent;
  let fixture: ComponentFixture<MessagesComponent>
  let store: Store<fromFeature.State>

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        StoreModule.forRoot({
          ...fromRoot.reducers,
          messagesModule: combineReducers(fromFeature.reducers),
        }),
    // other imports
      ],
      ...
    });

    store = TestBed.get(Store);

    spyOn(store, 'dispatch').and.callThrough();

    fixture = TestBed.createComponent(MessagesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

所以问题来了:测试失败是因为“找不到未定义的消息”。我安慰记录了我的测试组件,有存储。请有任何想法。

【问题讨论】:

  • 有同样的场景,同样的问题。在互联网上找不到任何东西......令人沮丧

标签: angular unit-testing karma-jasmine ngrx


【解决方案1】:

为了测试注入Store的组件,我关注了this official docs.

跟踪和删除 combineReducers 行对我有用。

   StoreModule.forRoot({
          ...fromRoot.reducers,
        }),

【讨论】:

    猜你喜欢
    • 2021-04-12
    • 2019-09-08
    • 1970-01-01
    • 2019-08-18
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    相关资源
    最近更新 更多