NgXs selectSnapshot在单元测试中不起作用

时间:2020-06-03 07:33:40

标签: unit-testing ngxs

这很清楚地描述了如何使用NgX编写单元测试 https://www.ngxs.io/recipes/unit-testing

如此模仿,我用SetLocale动作写了一个状态:

export class SetLocale {
  static readonly type = '[Internationalization] SetLocale';
  constructor(public value: string) { }
}

export class InternationalizationStateModel {
  locale: string;
}

@State<InternationalizationStateModel>({
  name: 'internationalization',
  defaults: {
    locale: null
  }
})
@Injectable({
  providedIn: 'root'
})
export class InternationalizationState {

  @Selector()
  static getLocale(state: InternationalizationStateModel): string {
    return state.locale;
  }

  @Action(SetLocale)
  setLocale(ctx: StateContext<InternationalizationStateModel>, { value }: SetLocale) {
    ctx.setState(
      patch({
        locale: value
      })
    );
  }
}

没有什么特别的,在代码中使用时效果很好。接下来添加了单元测试:

  let store: Store;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [NgxsModule.forRoot([InternationalizationState])],
    });
    store = TestBed.inject(Store);
  });

  it('should process locale', () => {
    store.dispatch(new SetLocale('xx-XX'));
    const locale = store.selectSnapshot(s => s.locale);
    expect(locale).toBe('xx-XX');
  });

据我所见,这正是指南所建议的方式,但是该测试因未定义语言环境而失败。

为什么?

1 个答案:

答案 0 :(得分:0)

看起来您只是缺少要快照的状态的名称:

尝试:store.selectSnapshot(s => s.internationalization.locale)

或使用选择器store.selectSnapshot(InternationalizationState.getLocale)