createSelector返回null,但仅在测试中

时间:2018-11-06 16:11:27

标签: angular jasmine karma-runner ngrx

我在ngrx选择器上进行了Jasmine单元测试。第一个可以正常工作,但是第二个总是返回未定义的,即使我可以看到减速器执行正确。

选择器如下:

export const selectProductState = createFeatureSelector<State, ProductState> (
  'product'
);

export const selectProductDetailsState = createSelector(
  selectProductState,
  ((state: ProductState) => state.product)
);

export const selectProduct = createSelector(
  selectProductDetailsState,
  ((state: ProductDetails) => state.product)
);

我的测试如下:

describe('selectProductDetailsState', () => {
  it('should return state of product store slice', () => {
    let result;

    store.pipe(
      select(fromSelectors.selectProductDetailsState)
    ).subscribe(value => ( result = value ));

    expect(result).toEqual(undefined);

    store.dispatch(new fromActions.LoadProductSummarySuccess(product));

    expect(result).toEqual(
      product
    );
  });
});

describe('selectProduct', () => {
  it('should return the product state', () => {
    let result;

    store.pipe(
      select(fromSelectors.selectProduct)
    ).subscribe(value => ( result = value ));

    expect(result).toEqual(undefined);

    store.dispatch(new fromActions.LoadProductSummarySuccess(product));

    expect(result).toEqual(product);
  });
});

selectProductDetailsState返回预期的产品,但是selectProduct返回未定义。

如果您还需要我的代码,只需大声喊叫。

这是我在测试中设置商店的方式:

describe('Product summary selectors', () => {
  let store: Store<State>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        StoreModule.forRoot(fromStore.reducers)
      ]
    });

    store = TestBed.get(Store);
  });
  // tests go here
})

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,可以通过包含一个空的根存储区来解决此问题,然后为您的方案导入StoreModule.forFeature,它看起来像这样:

describe('Product summary selectors', () => {
  let store: Store<State>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        StoreModule.forRoot({}),
        StoreModule.forFeature('products', fromStore.reducers)
      ]
    });

    store = TestBed.get(Store);
  });
  // tests go here
})

不确定它是否是最好的解决方案,但这是唯一对我有用的方法。