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

Angular测试:trimDelta方法多场景测试实现方案咨询

针对trimDelta方法的测试用例实现

首先明确原方法的核心逻辑:

遍历传入的ops数组,从第一个元素开始依次检查:若元素的insert为字符串且修剪后长度为0,则将其insert设为空字符串;一旦遇到不符合条件的元素,立即终止遍历,后续元素不会被处理。

以下基于Jest测试框架实现各场景的测试用例,你也可以适配其他测试框架(如Mocha):

场景1:无字符串类型的insert元素

测试传入的元素中,没有符合「insert是字符串且修剪后为空」条件的情况,方法应直接终止遍历,不修改任何元素。

test('无符合条件的字符串元素,不修改任何内容', () => {
  const ops = [
    { insert: 123 },
    { insert: { content: 'test' } },
    { delete: 3 },
    {}
  ];
  trimDelta(ops);
  expect(ops).toEqual([
    { insert: 123 },
    { insert: { content: 'test' } },
    { delete: 3 },
    {}
  ]);
});

场景2:字符串修剪后长度不为0

子场景2.1:第一个元素即为有效字符串

第一个元素的insert是修剪后非空的字符串,方法直接终止遍历,所有元素保持原样。

test('第一个元素是修剪后非空的字符串,不修改任何元素', () => {
  const ops = [
    { insert: '  hello world  ' },
    { insert: '   ' } // 此元素不会被处理,因为遍历提前终止
  ];
  trimDelta(ops);
  expect(ops).toEqual([
    { insert: '  hello world  ' },
    { insert: '   ' }
  ]);
});

子场景2.2:前序为空字符串,后续为有效字符串

前几个元素符合条件会被修改,遇到第一个有效字符串后终止遍历,后续元素不处理。

test('前序空字符串被修改,遇到有效字符串后终止遍历', () => {
  const ops = [
    { insert: '   ' },
    { insert: '\n\t' },
    { insert: '  test content  ' },
    { insert: ' ' } // 此元素不会被处理
  ];
  trimDelta(ops);
  expect(ops).toEqual([
    { insert: '' },
    { insert: '' },
    { insert: '  test content  ' },
    { insert: ' ' }
  ]);
});

场景3:仅含空字符串类型的元素

子场景3.1:所有元素均为修剪后为空的字符串

所有元素都会被遍历并修改为空字符串。

test('所有元素都是修剪后为空的字符串,全部替换为空', () => {
  const ops = [
    { insert: '   ' },
    { insert: '\n' },
    { insert: '\t ' },
    { insert: '' } // 本身为空,处理后不变
  ];
  trimDelta(ops);
  expect(ops).toEqual([
    { insert: '' },
    { insert: '' },
    { insert: '' },
    { insert: '' }
  ]);
});

子场景3.2:传入空数组

空数组不会触发遍历,无任何修改。

test('传入空数组,无任何操作', () => {
  const ops: any[] = [];
  trimDelta(ops);
  expect(ops).toEqual([]);
});

额外场景:混合类型且首元素为空字符串

首元素符合条件被修改,第二个元素为非字符串类型,遍历终止,后续元素不处理。

test('首元素为空字符串被修改,遇到非字符串元素后终止', () => {
  const ops = [
    { insert: ' ' },
    { insert: 456 },
    { insert: '   ' } // 此元素不会被处理
  ];
  trimDelta(ops);
  expect(ops).toEqual([
    { insert: '' },
    { insert: 456 },
    { insert: '   ' }
  ]);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 08:09:16