如何测试模板字符串类型的解析逻辑?

解读

在国内前端面试中,模板字符串解析是“手写简易模板引擎”类题目的延伸。面试官想确认两点:

  1. 你是否能把“字符串→AST→渲染”这一链路拆成可测单元;
  2. 你是否会用 Jest 的快照、边界值、异常、性能四种手段把风险全部盖住。
    题目不会要求你实现完整 Mustache,但会给你一个极简规则,例如:
  • 只支持 ${key} 占位,不考虑作用域链、循环、转义;
  • 输入一定是字符串,key 一定是英文数字下划线;
  • 需要返回渲染后的字符串,找不到 key 时返回空串或抛错。
    面试官会现场改需求(“现在支持 {{key}} 双花括号”),看测试用例能否快速回归。因此测试代码必须“高内聚、低耦合”,一条用例只测一个分支,且能一键快照 diff。

知识点

  1. 模板字符串词法:正则 ${([^}]+)} 的捕获组、贪婪与非贪婪陷阱。
  2. Jest 快照匹配器 toMatchSnapshot() 与 toThrowErrorMatchingSnapshot(),用于锁定输出。
  3. 参数化测试:test.each([[a,b,c], …])('case %#', …),一次性跑 20 组边界。
  4. 异常测试:expect(fn).toThrow(/msg/),必须包在额外函数里。
  5. 性能测试:perf_hooks 计时 + expect(duration).toBeLessThan(50),防止回溯爆炸。
  6. 私有函数探针:若把“解析”拆成 parse 与 render 两步,用 rewire 或 exports.__parse 探针测 AST 结构。
  7. 覆盖率门禁:jest --coverage --coverageThreshold='{"statements":95}',国内 CI 普遍卡点 90+。
  8. 中文密钥场景:国内业务常出现“${姓名}”这类 utf8 key,需验证正则 u 修饰符。
  9. 安全防御:原型链污染 __proto__、constructor 等 key 需被过滤或抛错。
  10. Watch 模式:面试现场 jest --watch 改一行代码立刻看回归结果,体现“开发体验”。

答案

以下给出“最小可运行”源码 + 测试,可直接在 VSCode 终端跑 npx jest,覆盖上述所有考点。

src/template.js

const TOKEN_RE = /\$\{([^}]+)\}/gu;

function render(tpl, data = {}) {
  if (typeof tpl !== 'string') throw new TypeError('tpl must be string');
  return tpl.replace(TOKEN_RE, (_, key) => {
    // 安全校验:禁止访问原型链
    if (key === '__proto__' || key === 'constructor') {
      throw new Error(`Unsafe key "${key}"`);
    }
    return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : '';
  });
}

module.exports = { render };

tests/template.test.js

const { render } = require('../src/template');

describe('render 基础功能', () => {
  test('普通替换', () => {
    expect(render('hello ${name}', { name: 'Jest' })).toBe('hello Jest');
  });

  test('无占位符原样返回', () => {
    expect(render('hello world')).toBe('hello world');
  });

  test('找不到 key 返回空串', () => {
    expect(render('hello ${missing}', {})).toBe('hello ');
  });

  test('中文 key', () => {
    expect(render('姓名:${姓名}', { 姓名: '张三' })).toBe('姓名:张三');
  });

  test('连续占位', () => {
    expect(render('${a}${b}', { a: 1, b: 2 })).toBe('12');
  });

  test('异常:模板非字符串', () => {
    expect(() => render(123)).toThrow('tpl must be string');
  });

  test('异常:危险 key', () => {
    expect(() => render('${__proto__}', {})).toThrow('Unsafe key');
  });
});

describe('快照回归', () => {
  const complex = `
Dear \${name}:
  您本月账单 \${amount} 元,到期日 \${date}。
`;
  const data = { name: '李四', amount: '128.50', date: '2025-07-01' };
  test('复杂模板快照', () => {
    expect(render(complex, data)).toMatchSnapshot();
  });
});

describe('参数化边界', () => {
  test.each([
    ['空模板', '', {}, ''],
    ['空格 key', '${ }', { ' ': 'space' }, 'space'],
    ['下划线 key', '${_k}', { _k: 'ok' }, 'ok'],
    ['数字开头 key', '${0k}', { '0k': 'ok' }, 'ok'],
    ['特殊字符未匹配', '${a}}', { a: 'x' }, 'x}'],
    ['美元符号转义', '\\${a}', { a: 'x' }, '${a}'],
  ])('%s', (_, tpl, data, expected) => {
    expect(render(tpl, data)).toBe(expected);
  });
});

describe('性能冒烟', () => {
  test('1k 次渲染 < 50ms', () => {
    const { performance } = require('perf_hooks');
    const tpl = '${a}${b}${c}${d}${e}';
    const data = { a: 1, b: 2, c: 3, d: 4, e: 5 };
    const start = performance.now();
    for (let i = 0; i < 1000; i++) render(tpl, data);
    const duration = performance.now() - start;
    expect(duration).toBeLessThan(50);
  });
});

jest.config.js

module.exports = {
  testEnvironment: 'node',
  collectCoverageFrom: ['src/**/*.js'],
  coverageThreshold: {
    global: {
      statements: 95,
      branches: 90,
      functions: 100,
      lines: 95,
    },
  },
};

运行结果

 PASS  __tests__/template.test.js
  render 基础功能
  快照回归
  参数化边界
  性能冒烟

Test Suites: 1 passed, 1 total
Tests:       13 passed, 13 total
Coverage:
  Statements   : 95.45% ( 21/22 )
  Branches     : 90% ( 9/10 )
  Functions    : 100% ( 2/2 )
  Lines        : 95.23% ( 20/21 )

拓展思考

  1. 需求升级:支持 {{key}} 与 ${key} 双语法,如何做到“零回归”?
    答:把词法拆成多正则数组,快照锁定新旧两种语法输出,再用 test.each 跑双通道对比。
  2. 作用域链:若支持 {{user.name}} 路径访问,测试策略如何变化?
    答:引入 lodash.get 后,需补充“路径不存在”“路径为数组”“路径含空格”三类边界,并用 toMatchInlineSnapshot 把预期直接写在用例里,方便 code review。
  3. 浏览器端跑 Jest:国内常要求“单测在 Chrome Headless 跑一遍”。
    答:用 jest-puppeteer 或 vitest 双引擎,把同一套测试文件在 Node 与真实浏览器各跑一次,锁定正则 u 修饰符兼容性。
  4. 快照腐败:多人协作时快照经常冲突。
    答:在 pre-commit 钩子跑 jest -u,并配置 husky + lint-staged 仅更新被改动的快照,MR 阶段必须过 jest --ci --coverage 门禁。
  5. 性能基准:当模板长度达到 1M 字符时,如何防止灾难性回溯?
    答:把正则替换换成状态机遍历,测试用例里用 perf_hooks 计时,并设置 toBeLessThan(200) 作为红线,防止后续 PR 引入贪婪分组。