NgXs selectSnapshot 在单元测试中不起作用
NgXs selectSnapshot not working in unit test
这非常清楚地描述了如何使用 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');
});
据我所知,这正是指南所建议的,但由于语言环境未定义,此测试失败了。
为什么?
看起来您只是遗漏了要拍摄快照的状态的名称:
尝试:store.selectSnapshot(s => s.internationalization.locale)
或使用您的选择器store.selectSnapshot(InternationalizationState.getLocale)
这非常清楚地描述了如何使用 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');
});
据我所知,这正是指南所建议的,但由于语言环境未定义,此测试失败了。
为什么?
看起来您只是遗漏了要拍摄快照的状态的名称:
尝试:store.selectSnapshot(s => s.internationalization.locale)
或使用您的选择器store.selectSnapshot(InternationalizationState.getLocale)