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

求助:使用Jest为TypeScript Sections类编写指定校验规则的测试用例

嘿,刚上手Jest完全不用焦虑,我这就帮你写出符合要求的测试用例!首先咱们得明确测试的核心目标:确保传入getSections的参数是一个数组,而且数组里的每一项都满足CallId和SectionId是数字类型,SectionName是字符串类型。

先给你补全完整的类代码(你之前的代码没写完导出部分,我帮你补上):

class Sections {
  constructor() { }
  public getSections(section: Array<{CallId: number; SectionId: number; SectionName: string}>): void {
    for (let k = 0; k < section.length; k++){
      console.log(`CallId: ${section[k].CallId}, SectionId: ${section[k].SectionId}, SectionName: ${section[k].SectionName}`);
    }
  }
}

export default Sections;

这里给参数加了TypeScript类型注解做静态检查,搭配Jest的运行时测试,能形成双重校验~

接下来是Jest测试用例,我分几个场景覆盖合法、非法输入的情况:

import Sections from './sections'; // 替换成你的实际文件路径

describe('Sections.getSections', () => {
  let sectionsInstance: Sections;

  beforeEach(() => {
    sectionsInstance = new Sections();
    // 清空console.log的记录,避免测试之间互相干扰
    jest.spyOn(console, 'log').mockImplementation(() => {});
  });

  afterEach(() => {
    // 测试结束后恢复console.log的原有功能
    jest.restoreAllMocks();
  });

  it('should run smoothly with a valid array of sections', () => {
    const validSections = [
      { CallId: 123, SectionId: 456, SectionName: 'First Section' },
      { CallId: 789, SectionId: 101, SectionName: 'Second Section' }
    ];

    // 执行方法,不应该抛出任何错误
    expect(() => sectionsInstance.getSections(validSections)).not.toThrow();
    // 额外验证console.log被调用了对应次数
    expect(console.log).toHaveBeenCalledTimes(validSections.length);
  });

  it('should throw an error when input is not an array', () => {
    const invalidInputs = [
      { CallId: 1, SectionId: 2, SectionName: 'Single Object' }, // 单个对象而非数组
      'random string',
      null,
      undefined,
      12345
    ];

    invalidInputs.forEach(input => {
      expect(() => sectionsInstance.getSections(input as any)).toThrow();
    });
  });

  it('should throw an error when section items have invalid property types or missing properties', () => {
    const invalidSectionItems = [
      // CallId不是数字类型
      { CallId: '123', SectionId: 456, SectionName: 'Wrong CallId Type' },
      // SectionId不是数字类型
      { CallId: 123, SectionId: '456', SectionName: 'Wrong SectionId Type' },
      // SectionName不是字符串类型
      { CallId: 123, SectionId: 456, SectionName: 789 },
      // 缺少SectionId属性
      { CallId: 123, SectionName: 'Missing SectionId' }
    ];

    invalidSectionItems.forEach(item => {
      expect(() => sectionsInstance.getSections([item] as any)).toThrow();
    });
  });
});

这里要提个小细节:原方法本身没有做运行时的类型校验,所以如果只是依赖TypeScript编译检查,运行时传入类型错误的参数可能只会打印undefined而不报错。我建议你给getSections加上运行时校验逻辑,这样测试用例的错误断言会更精准,修改后的方法如下:

public getSections(section: Array<{CallId: number; SectionId: number; SectionName: string}>): void {
  // 先校验输入是否为数组
  if (!Array.isArray(section)) {
    throw new Error('Input must be an array of sections');
  }

  section.forEach((item, index) => {
    // 逐个校验属性的类型和存在性
    if (typeof item.CallId !== 'number') {
      throw new Error(`Section at index ${index} has invalid CallId: must be a number`);
    }
    if (typeof item.SectionId !== 'number') {
      throw new Error(`Section at index ${index} has invalid SectionId: must be a number`);
    }
    if (typeof item.SectionName !== 'string') {
      throw new Error(`Section at index ${index} has invalid SectionName: must be a string`);
    }

    console.log(`CallId: ${item.CallId}, SectionId: ${item.SectionId}, SectionName: ${item.SectionName}`);
  });
}

这样修改后,测试用例里的错误场景就能准确触发,真正实现输入合法性的校验啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:04:02