如何测试这个特定的选择器?

时间:2019-12-23 21:20:25

标签: angular karma-jasmine ngrx

我正在测试我的NgRx代码,在选择器上我有两个选择器:

export const selectSlice = (state: AppState) => state.slice;

export const selectErrors = createSelector(
  selectSlice,
  state => state.errors
);

我可以使用投影机很容易地测试selectErrors,但是我不能测试第一个,它在Instanbul上始终保持“未发现功能”。我尝试了以下方法:

it('should return call to selectSlice', () => {
    const selector = selectors.selectSlice;
    store.select(selector);

    expect(store.select).toHaveBeenCalledWith(selector);
});

我应该如何测试?

编辑:这是我对错误选择器的测试:

it('should return call to selectErrors', () => {
    const selector = selectors.selectErrors;
    store.select(selector);

    expect(store.select).toHaveBeenCalledWith(selector);
    expect(
      selector.projector({
        errors: [
          {
            message: 'Mock error'
          }
        ]
      }).length
    ).toEqual(1);
  });

1 个答案:

答案 0 :(得分:1)

该功能未被发现,因为您正在使用选择器的projector函数,该函数将跳过执行选择器,而仅运行投影仪功能。

要获得代码覆盖,您应该:

  • 不要使用projector函数,因为它是一个相当简单的选择器
  • 或为其编写测试,如下所示(由于选择器只是一个函数,因此可以调用它并测试输出):
expect(selectSlice({ slice: 'foo'})).toEqual('foo')

我个人认为编写这些测试没有任何附加价值,而且这些测试可能很耗时-有关更多信息,请参见我的文章How I test my NgRx selectors