如何使用 @parcel/test-utils 在 Jest 中启动“内存构建”并断言输出文件内容?请给出最小测试模板。
解读
- 面试场景:国内一线/二线前端团队普遍用 Jest 做单测,Parcel 作为零配置构建工具,其官方提供的
@parcel/test-utils能把整个构建跑在内存里,不落地磁盘,速度极快,特别适合 CI。 - 考点定位:
- 是否知道 Parcel 的“内存文件系统”能力(MemoryFS)
- 是否会把
@parcel/test-utils的bundler与getNextBuild正确接入 Jest - 是否会用
outputFS.readFileSync读取产物并断言,而不是去读真实磁盘
- 易错点:
- 忘记
await getNextBuild(bundler),导致拿到旧产物 - 把
distDir写成绝对路径,CI 上路径变化导致用例挂 - 直接
fs.readFileSync读磁盘,本地能跑,CI 挂
- 忘记
知识点
@parcel/test-utils暴露的核心 APIcreateTestBundler(entry, { targets, distDir, ... }):返回一个 Bundler 实例,内部已挂载 MemoryFSgetNextBuild(bundler):等待下一次构建结束,返回 BuildResult,含bundleGraphoutputFS:即 MemoryFS 实例,提供readFileSync、existsSync等同步 API
- Jest 中“最小模板”需满足
- 单文件即可运行,无额外配置文件
- 用
expect断言产物内容,而非快照 - 用
afterAll关闭 bundler,防止句柄泄漏
- 国内 CI 常见镜像源问题:若用
pnpm,需在jest.config.js里把transformIgnorePatterns配成允许@parcel被 babel-jest 转译,否则跑不动
答案
// __tests__/parcel-memory-build.spec.js
const path = require('path');
const { createTestBundler, getNextBuild } = require('@parcel/test-utils');
// 产物落地目录随意写,MemoryFS 不会真写磁盘
const distDir = path.join(__dirname, '../.parcel-test-dist');
describe('Parcel 内存构建', () => {
let bundler;
afterAll(async () => {
if (bundler) await bundler.stop();
});
test('应正确输出 index.js 并包含预期代码', async () => {
const entry = path.join(__dirname, 'fixtures/index.js');
bundler = createTestBundler(entry, {
targets: { main: { distDir, outputFormat: 'esmodule' } },
mode: 'production',
sourceMaps: false,
});
// 等待首次构建完成
await getNextBuild(bundler);
// 从内存文件系统读取产物
const outputPath = path.join(distDir, 'index.js');
const content = bundler.options.outputFS.readFileSync(outputPath, 'utf8');
// 简单断言:产物里应该被 Tree-Shaking 掉未引用变量
expect(content).toContain('console.log("hello parcel")');
expect(content).not.toContain('unusedVar');
});
});
fixtures/index.js
const unusedVar = 42;
console.log('hello parcel');
运行
jest __tests__/parcel-memory-build.spec.js
即可在 1s 内完成“零磁盘 IO”的构建断言。
拓展思考
- 多入口场景:把
createTestBundler的entry换成数组或 glob,断言多个产物是否都生成,且共享的 chunk 是否被正确拆出。 - 热更新链路:在同一个测试文件里连续改
fixtures/index.js,调用getNextBuild两次,对比两次产物哈希,验证缓存是否生效。 - 异常分支:故意写一段无法解析的
import './not-exist.vue',断言getNextBuild抛出的BuildError中diagnostics[0].message是否包含“Cannot resolve”。 - 与 GitHub Actions 集成:把上述用例放到
workflow.yml,利用actions/cache缓存.parcel-cache,可把 CI 构建测试耗时压到 10s 以内,满足国内“分钟级流水线”要求。