You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular升级至13后NGXS测试中Jasmine withArgs类型错误咨询

解决NGXS中selectSnapshot与withArgs的类型不匹配问题

问题原因

Angular升级到13+TypeScript4.6后,类型检查规则更严格,NGXS的@Selector装饰器生成的函数类型,与JasminewithArgs()期望的StateToken<unknown> | AsymmetricMatcher<any>类型不兼容,从而触发类型报错。

解决方案

1. 升级NGXS到兼容Angular 13的版本

旧版本NGXS的类型定义未适配TypeScript 4.6及Angular 13的要求,升级到对应兼容版本可直接解决类型冲突:

  • Angular 13对应NGXS 4.x系列(如4.0.0及以上)
    执行安装命令:
npm i @ngxs/store@4.x @ngxs/logger-plugin@4.x @ngxs/devtools-plugin@4.x --save

2. 类型断言临时兼容

若暂时无法升级NGXS,可通过类型断言将Selector转换为withArgs()接受的类型,替代@ts-ignore:

import { StateToken } from '@ngxs/store';

// ...

spyOn(store, 'selectSnapshot')
  .withArgs(ExampleState.clinic as unknown as StateToken<Example>)
  .and.returnValue({ id: 1 });

3. 自定义Jasmine匹配器精确匹配Selector

若需要更严格的类型安全,可自定义匹配器识别NGXS Selector函数:

beforeEach(() => {
  jasmine.addMatchers({
    toBeNgxsSelector: () => ({
      compare: (actual: unknown, expected: Function) => {
        const isSelector = typeof actual === 'function' && actual.hasOwnProperty('selectorOptions');
        return {
          pass: isSelector && actual === expected,
          message: isSelector ? `Expected selector to be ${expected.name}` : 'Value is not an NGXS Selector'
        };
      }
    })
  });
});

// 使用自定义匹配器
spyOn(store, 'selectSnapshot')
  .withArgs(jasmine.matchers.toBeNgxsSelector(ExampleState.clinic))
  .and.returnValue({ id: 1 });

内容的提问来源于stack exchange,提问作者Brendan Murphy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 16:40:26