单元测试Angular组件+ ngrx存储

问题描述 投票:2回答:1

试图测试我的角度分量。

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

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个回答
0
投票

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

执行以下操作并删除co​​mbineReducers行为我工作。

   StoreModule.forRoot({
          ...fromRoot.reducers,
        }),
© www.soinside.com 2019 - 2024. All rights reserved.