DOM 测试
一句话解释
DOM 测试验证 code 那个 manipulates web page 结构, using simulated DOM (jsdom) in 节点.js or 真实浏览器.
用大白话说
DOM 测试是 for code 那个 interacts 使用 web page — 创建元素, 更改文本, handling 事件, etc. 由于这个 code 需要 DOM 到工作, 你需要 DOM 环境 for 测试.
Two 方法:
- jsdom: pure JavaScript DOM simulation 那个运行 in 节点.js. 快, 否浏览器需要, 但 doesn't support 布局/渲染 or 所有浏览器 APIs.
- Real browser: Use Playwright or Cypress 到测试 in 实际浏览器. Slower 但 fully realistic.
For 单元 and 组件测试, jsdom 是通常 sufficient and much faster. Jest uses jsdom 通过默认 for 浏览器-环境测试. For E2E 测试, 你需要真实浏览器.
DOM 测试库 如测试库 help 你查询元素 and simulate 用户 interactions in simulated DOM.
示例
javascript
// dom.test.js — Testing DOM with Testing Library
import { render, screen, fireEvent } from '@testing-library/dom';
import { createButton } from './button';
test('button increments count on click', () => {
const container = document.createElement('div');
createButton(container); // renders <button>Count: 0</button>
const btn = screen.getByText(/Count:/);
fireEvent.click(btn);
fireEvent.click(btn);
expect(btn.textContent).toBe('Count: 2');
});
// Tests interact with real DOM nodes (created in jsdom)
// and assert on what the user actually sees.DOM 测试将组件渲染到真实(jsdom)DOM 中,通过 fireEvent 交互并断言可见文本——测试用户看到的内容,而非组件内部状态。
相关术语
相关资源
相关课程
- DOM 测试
测试 DOM manipulation.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。