【问题标题】:Angular Ngrx Test: Store.overrideSelector does not overrideAngular Ngrx 测试:Store.overrideSelector 不会覆盖
【发布时间】:2020-03-09 11:16:20
【问题描述】:

我确实有以下beforeEach

beforeEach(() => {
    fixture = TestBed.createComponent(ApplyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    store = TestBed.get<Store<fromAnnouncement.AnnouncementState>>(Store);
    store.refreshState();
    mockApplicationSelector = store.overrideSelector(selectDraftApplication, testDraftApplication); <-- Try to mock  a selector here.
  });

选择器 selectDraftApplication 依赖于 AnnouncementState 的特征选择器,其中有两个实体,其中一个是使用特征选择器进行子选择以构建我的 selectDraftApplication 选择器。

在测试中使用此代码时,我的所有测试都崩溃了,因为 NgRx 似乎仍然在进一步寻找所有状态,而我希望模拟能够精确地阻止这种情况。模拟整个 ngrx 实体存储是没有意义的,所以我只希望选择器准确地返回该对象并完成它。我用谷歌搜索了很远,但没有得到任何答案。有什么帮助吗?我运行 Angular 8 和 ngrx 8.5.1(refreshState() 函数也不起作用......)

谢谢!

编辑

export const getAnnouncementState = createFeatureSelector<AnnouncementState>('announcement');

export const getApplicationsState = createSelector(
  getAnnouncementState,
  (state: AnnouncementState) => state.applications 
);

export const selectDraftApplication = createSelector(
  getApplicationsState,
  (state: ApplicationState) => state.draftApplication
);

【问题讨论】:

  • 选择器长什么样?
  • 嗨@timdeschryver。我添加了选择器链。测试在第二个中中断,其中选择了应用程序(它不存在,因为我必须模拟一个 ngrx 实体来执行此操作)。我感兴趣的只是选择一个draftApplication
  • 恕我直言,如果你有复制品我很乐意看看
  • 这里有同样的问题:stackoverflow.com/questions/58787505/…。 (快速回答,我不认为模拟选择器是最好的主意,但这里有替代方案)
  • 请不要再写了,覆盖选择器不是一个好主意。这就像为测试设置输入一样。最纯粹的单元测试。如果您不需要测试状态集成,这是最好的方法!

标签: angular unit-testing ngrx angular-test


【解决方案1】:

模拟选择器后需要调用refreshState()...

beforeEach(() => {
    fixture = TestBed.createComponent(ApplyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    store = TestBed.get<Store<fromAnnouncement.AnnouncementState>>(Store);
    //
    mockApplicationSelector = store.overrideSelector(selectDraftApplication, testDraftApplication); <-- Try to mock  a selector here.

    store.refreshState(); <-- refresh state ***after*** mocking the selector
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-05
    • 2016-07-09
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多