这非常清楚地描述了如何使用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');
});据我所知,这正是指南的建议,但由于语言环境未定义,此测试失败。
为什么?
发布于 2020-06-04 11:49:41
看起来您只是缺少要创建快照的状态的名称:
尝试:store.selectSnapshot(s => s.internationalization.locale)
或者使用选择器store.selectSnapshot(InternationalizationState.getLocale)
https://stackoverflow.com/questions/62167513
复制相似问题