jsdom
一句话解释
jsdom 是 fake DOM implemented in JavaScript — 它 lets 你测试 DOM code in 节点.js 不使用 launching 真实浏览器.
用大白话说
jsdom 是 JavaScript 库那个 simulates DOM (Document 对象 Model) in 节点.js. 它 implements enough 的 HTML and DOM 标准那个你 能测试浏览器 code 不使用真实浏览器.
With jsdom, 你获取 document, window, navigator, and other 浏览器 globals in 你的节点.js 测试环境. 你能 创建元素, 修改 DOM, dispatch 事件, and 查询元素 — 所有 in 快, headless 节点.js.
Jest uses jsdom 通过默认当 你设置 testEnvironment: 'jsdom'. 这个是 如何 Jest 能测试 React 组件 (哪个需要 DOM) 不使用 launching Chrome.
Limitations: jsdom doesn't 做实际布局 or 渲染 (否 visual 输出), doesn't support 一些浏览器 APIs (如 canvas, IntersectionObserver), and 有否 CSS 布局 engine. For 那些, 你需要真实浏览器.
示例
// jsdom simulates the DOM in Node.js (no browser needed)
import { JSDOM } from 'jsdom';
const dom = new JSDOM('<!DOCTYPE html><div id="app"></div>');
const document = dom.window.document;
// Now you can manipulate the DOM as if in a browser:
const app = document.getElementById('app');
const btn = document.createElement('button');
btn.textContent = 'Click me';
btn.addEventListener('click', () => {
btn.textContent = 'Clicked!';
});
app.appendChild(btn);
// Simulate a click
btn.click();
console.log(btn.textContent); // 'Clicked!'
// Vitest/Jest use jsdom automatically in test filesjsdom 在 Node.js 中创建模拟 DOM,无需浏览器即可运行依赖 DOM 的测试。它实现了足够的 DOM API(createElement、addEventListener 等)来满足大多数单元测试。
相关术语
相关资源
相关课程
- DOM 测试
测试 DOM manipulation.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。