首页 > 解决方案 > NgXs selectSnapshot 在单元测试中不起作用

问题描述

这非常清楚地描述了如何使用 NgXs 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');
  });

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

为什么?

标签: unit-testingngxs

解决方案


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

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

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


推荐阅读