如何在 Jest 中模拟 Custom Element 的生命周期?
解读
国内前端项目普遍采用 Webpack 打包,组件库、微前端、低代码平台又大量依赖原生 Custom Element。面试时,考官想确认两点:
- 你是否知道 Jest 默认跑在 JSDOM 环境,而 JSDOM 只实现了 V1 版 Custom Element 的“最小子集”,很多生命周期钩子(adoptedCallback、完整的 observedAttributes 触发链)并不可靠;
- 你是否能用 Webpack 生态的常用手段(babel-loader + @babel/plugin-transform-classes、jest-environment-jsdom、jest-transform-stub 等)把“缺失的浏览器行为”补齐,让单元测试既跑得快又能覆盖生命周期。
因此,回答要体现“环境补全 + 手动调度 + 断言时机”三板斧,并顺带说明 Webpack 侧如何给测试包打补丁,而不是单纯贴代码。
知识点
- Custom Element V1 四个生命周期:constructor、connectedCallback、disconnectedCallback、attributeChangedCallback(plus adoptedCallback)。
- JSDOM 的缺口:
– 不触发 adoptedCallback;
– attributeChangedCallback 只在 attribute 显式 set/remove 时触发,且不会自动比较 oldValue;
– 不会自动调用 constructor 中的 upgrade 过程。 - Jest 运行时顺序:environment → setupFiles → transform → test;因此补丁必须在 environment 或 setupFiles 阶段注入。
- Webpack 侧给测试 bundle 打补丁的两种姿势:
– 通过 jest.config.js 的 setupFilesAfterEnv 把补丁脚本插到所有 test 之前;
– 在 webpack.config.test.js 里用 DefinePlugin 注入 TEST 标记,让源码在测试环境走降级分支。 - 手动调度:使用 Element.attachShadow、customElements.upgrade、customElements.get、customElements.whenDefined 等 API 模拟浏览器升级时机。
- 断言时机:必须 await customElements.whenDefined(tagName) 后再 nextTick/flushPromises,否则会出现“钩子未执行完就断言”的假绿。
- 内存泄漏防控:每次 test 后把自定义元素从 registry 中移除(customElements.define 只能升级一次,需借助 jest.isolateModules 或独立 window)。
答案
-
环境补全
在 jest.config.js 中指定 testEnvironment: 'jsdom',并新建 tests/setup-custom-element.js:// 补全 adoptedCallback 触发能力 if (!global.window.customElements) { throw new Error('请升级 jest-environment-jsdom 到 28+'); } const originalAdoptNode = global.window.Document.prototype.adoptNode; global.window.Document.prototype.adoptNode = function (node) { const adopted = originalAdoptNode.call(this, node); if (adopted instanceof global.window.HTMLElement && adopted.adoptedCallback) { adopted.adoptedCallback(); } return adopted; }; // 补全 attribute 变更比对 const originalSetAttr = global.window.Element.prototype.setAttribute; global.window.Element.prototype.setAttribute = function (qn, val) { const old = this.getAttribute(qn); originalSetAttr.call(this, qn, val); if (this.attributeChangedCallback && this.constructor.observedAttributes && this.constructor.observedAttributes.includes(qn)) { this.attributeChangedCallback(qn, old, val); } };然后在 setupFilesAfterEnv: ['<rootDir>/tests/setup-custom-element.js'] 中引入。
-
手动调度生命周期
测试文件:import { flushPromises } from './test-utils'; describe('MyEl 生命周期', () => { let MyEl; beforeAll(async () => { // 使用 Webpack 的 dynamic import 语法,确保走 babel-loader 转译后的类 const module = await import('../src/my-el.js'); MyEl = module.default; customElements.define('my-el', MyEl); await customElements.whenDefined('my-el'); }); afterAll(() => { // 清注册表,防止跨 case 污染 jest.isolateModules(() => { // 重新加载会生成新的 registry }); }); it('应触发 connectedCallback', async () => { const el = document.createElement('my-el'); const spy = jest.spyOn(el, 'connectedCallback'); document.body.appendChild(el); await flushPromises(); expect(spy).toHaveBeenCalledTimes(1); }); it('应触发 attributeChangedCallback', async () => { const el = document.createElement('my-el'); document.body.appendChild(el); el.setAttribute('size', 'large'); // 走我们补全的 setAttribute await flushPromises(); expect(el.changeRecord).toEqual({ name: 'size', old: null, new: 'large' }); }); it('应触发 adoptedCallback', async () => { const el = document.createElement('my-el'); const spy = jest.spyOn(el, 'adoptedCallback'); const newDoc = global.window.document.implementation.createHTMLDocument(); newDoc.adoptNode(el); // 会走到我们的补丁 await flushPromises(); expect(spy).toHaveBeenCalledTimes(1); }); }); -
Webpack 侧配置(可选,但面试提到会加分)
webpack.config.test.js:module.exports = { mode: 'development', target: 'node', // 让 Webpack 不打包 Node 内置模块 module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: [ ['@babel/preset-env', { targets: { node: 'current' } }] ], plugins: [ ['@babel/plugin-transform-classes', { loose: true }] // 防止 JSDOM 原生类冲突 ] } } }, { test: /\.css$/, use: 'jest-transform-stub' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('test') }) ] };这样 Jest 在 transform 时会复用 Webpack 的 babel-loader,保证 Custom Element 的类语法被正确转译,且与生产构建保持一致。
拓展思考
- 如果项目用 Webpack Module Federation 把 Custom Element 作为远程组件暴露,测试时需要先启动 federation-static-server,再用 puppeteer 跑 e2e,单元层只需 mock 远程入口,避免重复定义。
- 对于 Shadow DOM 内的样式断言,可以结合 jest-styled-components 的 styleSheetSerializer,但要在 setup 里把 ‘window.ShadyCSS’ 设为 undefined,强制走原生 Shadow CSS,防止 JSDOM 警告。
- 在 CI 环境,为了让测试并发安全,可用 jest-environment-node + happy-dom 替代 jsdom,happy-dom 的 Custom Element 实现更接近浏览器,但体积更小,Webpack 打包速度提升约 20%。
- 若公司代码规范要求“必须 100% 覆盖生命周期”,可在 Webpack 侧写一个自定义 plugin,在编译时注入 coverage 标记,把 connectedCallback 等钩子拆分为可单元测试的纯函数,再用 Jest mock 调用,实现“行覆盖+分支覆盖”双达标。