如何用 `sass-true` 对函数做单元测试?

解读

国内前端团队对 Sass 的依赖已从“写变量”进阶到“写框架”,函数库(如 px→rem、颜色混合、栅格计算)越来越复杂。面试官问“怎么给 Sass 函数写单测”,核心想确认三件事:

  1. 你是否知道 Sass 本身没有断言,必须借助外部工具;
  2. 你是否用过 sass-true 这一国内大厂都在用的主流方案(阿里、美团、滴滴的组件仓库均可见);
  3. 你是否能把测试脚本与 Webpack/Vite/Rollup 构建流程打通,让单测在 CI 卡点生效。
    答不出“真跑起来”,只会背语法,会被直接判负。

知识点

  • sass-true 定位:专为 Sass 设计的单元测试框架,提供 assert-equal、assert-true、assert-false 等断言,输出 TAP 格式结果,可被 Jest、Mocha 消费。
  • 运行模式:
    – Node 端:sass-true + jest 最快,国内项目 90% 选它;
    – Dart-Sass 模式:必须显式指定 sass 包,避免 node-sass 遗留 bug。
  • 用例写法:测试文件必须以 _test.scss 或 _spec.scss 结尾,使用 true.run() 把模块注册给 JS 入口。
  • 断言粒度:函数返回值为 Number、String、Color、List、Map、Boolean 均可断言,不支持直接比较自定义对象。
  • CI 卡点:在 package.json 里加 "test": "jest sass",配合 husky 的 pre-push 钩子,国内 GitLab 流水线普遍这样拦代码。
  • 性能注意:sass-true 会把每个断言编译成独立 CSS,用例过多时冷启动 >3 s,建议把函数与 mixin 分文件、分套件,减少重复 @import。

答案

  1. 安装依赖(国内镜像示例)
npm i -D sass-true sass jest  # 用 dart-sass,别装 node-sass
  1. 新建 tests/scss/_px-to-rem.test.scss
@use 'true' as *;
@use '../../src/styles/helpers/math' as *;

@include test-module('px-to-rem') {
  @include test('should convert 32px to 2rem with base 16') {
    @include assert-equal(px-to-rem(32px, 16px), 2rem);
  }

  @include test('should return 0 when input 0') {
    @include assert-equal(px-to-rem(0), 0rem);
  }
}
  1. 新建 tests/scss/index.test.js(Jest 入口)
const path = require('path');
const sassTrue = require('sass-true');

// 把 sass-true 的 runner 交给 Jest
sassTrue.runSass({ file: path.resolve(__dirname, 'scss/_px-to-rem.test.scss') }, describe, it);
  1. 在 package.json 补脚本
"scripts": {
  "test:sass": "jest tests/scss/index.test.js",
  "test": "npm run test:sass && jest"   // 双通道,同时跑 JS 与 Sass 单测
}
  1. 本地验证 & CI 卡点
npm run test:sass

若断言失败,终端会打印 TAP 风格日志,直接定位行号;GitLab CI 里只要 npm test 返回非 0,合并请求即被驳回。

拓展思考

  • 真值表测试:颜色函数常出现浮点误差,可封装 _approx-equal 断言,允许 1‰ 误差,再让 sass-true 调用。
  • 与 Stylelint 联动:在 pre-commit 阶段先 stylelint --fix,再跑 sass-true,保证风格与逻辑双达标。
  • 快照测试:对复杂 Map 返回值,可用 sass-true 的 assert-equal 结合 Jest 快照,把第一次编译结果写入 __snapshots__,后续 diff 即可。
  • 性能基准:在大型组件库(如 Ant Design 的 theme 包)里,建议把函数测试与构建脚本分离,夜间定时跑,避免阻塞本地开发。
  • 向面试官反问:可以追问“贵司是否把 Sass 函数单测纳入覆盖率统计?”——如果对方答“用 Istanbul 合并 JS 与 Sass 报告”,说明团队基建成熟;若答“只跑编译”,则你可提出引入 sass-true + nyc 合并方案,直接体现落地能力。