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

Angular 5项目中Jasmine Fake的TypeScript元组键字典实现咨询

嘿,这个需求很常见——做一个能根据多参数组合返回预设结果的Jasmine Fake对吧?用元组作为键的思路完全可行,在TypeScript里我们可以用Map或者字符串化的对象来实现,下面给你详细的方案:

第一步:定义核心类型

首先先把你需要的参数元组和结果类型明确下来,这里假设ListTypes是你已经定义好的枚举或联合类型,我先写个示例:

// 替换成你实际的ListTypes定义
type ListTypes = 'userList' | 'productList' | 'orderList';

// 定义多参数元组,对应你需要的三个参数类型
type FakeParams = [string, ListTypes, string];

// 定义Fake要返回的结果类型,这里用string示例,你可以换成实际的类型(比如接口、数组等)
type FakeResult = string;
第二步:用Map实现Fake(推荐)

TypeScript的Map支持任意类型作为键,包括元组,这比普通对象更直观,也不会出现键冲突的问题。我们可以封装一个Fake类:

class MyTargetServiceFake {
  // 用Map存储「参数元组」和「对应结果」的映射
  private resultMap = new Map<FakeParams, FakeResult>();

  // 提供方法来预设参数组合对应的结果
  public setMockResult(params: FakeParams, result: FakeResult): void {
    this.resultMap.set(params, result);
  }

  // 模拟目标方法,根据传入的参数返回预设结果
  public targetMethod(param1: string, param2: ListTypes, param3: string): FakeResult {
    const params: FakeParams = [param1, param2, param3];
    const matchedResult = this.resultMap.get(params);

    // 如果没有匹配到预设结果,可以抛出错误或者返回默认值,按需调整
    if (!matchedResult) {
      throw new Error(`No mock result configured for params: ${JSON.stringify(params)}`);
    }

    return matchedResult;
  }
}
第三步:在Jasmine测试中使用

在你的测试套件里,初始化Fake实例,预设不同参数组合的结果,然后验证逻辑:

describe('MyComponent', () => {
  let serviceFake: MyTargetServiceFake;

  beforeEach(() => {
    serviceFake = new MyTargetServiceFake();
    // 预设多组参数对应的结果
    serviceFake.setMockResult(['admin', 'userList', 'active'], '[{"id":1,"name":"Alice"}]');
    serviceFake.setMockResult(['guest', 'productList', 'featured'], '[{"id":101,"name":"Laptop"}]');
  });

  it('should return the correct mock result for matched params', () => {
    expect(serviceFake.targetMethod('admin', 'userList', 'active')).toBe('[{"id":1,"name":"Alice"}]');
    expect(serviceFake.targetMethod('guest', 'productList', 'featured')).toBe('[{"id":101,"name":"Laptop"}]');
  });

  it('should throw error when no mock result is configured for params', () => {
    expect(() => serviceFake.targetMethod('unknown', 'orderList', 'all')).toThrowError();
  });
});
备选方案:用普通对象实现(字符串化键)

如果你更习惯用普通对象,因为TypeScript对象的键只能是字符串/数字/symbol,我们可以把元组字符串化作为键:

class MyTargetServiceFakeWithObject {
  private resultDict: Record<string, FakeResult> = {};

  public setMockResult(params: FakeParams, result: FakeResult): void {
    // 把元组转成唯一字符串作为键
    const key = JSON.stringify(params);
    this.resultDict[key] = result;
  }

  public targetMethod(param1: string, param2: ListTypes, param3: string): FakeResult {
    const params: FakeParams = [param1, param2, param3];
    const key = JSON.stringify(params);
    const matchedResult = this.resultDict[key];

    if (!matchedResult) {
      throw new Error(`No mock result configured for params: ${JSON.stringify(params)}`);
    }

    return matchedResult;
  }
}

这种方式也能工作,但要注意:如果参数里包含特殊字符(比如逗号),理论上可能出现键冲突,但大部分业务场景下不会有问题。相比之下,Map的方案更安全直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:44:14