unit-testing - 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');
});
据我所知,这正是指南所建议的方式,但是由于未定义语言环境,因此该测试失败。
为什么?
解决方案
看起来您只是缺少要快照的状态的名称:
尝试:store.selectSnapshot(s => s.internationalization.locale)
或使用您的选择器store.selectSnapshot(InternationalizationState.getLocale)
推荐阅读
- javascript - 如何在 Laravel 刀片中的反应组件中获取 Laravel 验证错误
- javascript - Node.js - 定义了一个函数但引发错误
- c# - 无法在 ASP.NET Core 操作筛选器中获取正确的 DbContext 引用
- reactjs - 如何在 nextjs 的 getInitialProps stateles 组件中访问路由器参数
- node.js - 为 prometheus 检测 Google AppEngine 应用程序
- django - 继承一个类但只使用必填字段,而不是所有继承的字段
- xml - 博主 Soho:主页中缺少原始替代文字
- python - 使用机器学习获取图像输入并获得 3 个浮点输出
- unity3d - 使用 Vuforia 图像目标显示 2d 图像
- pytorch - 有没有另一种方法来保存保存损失和学习率的图表