# inject-jsdom **Repository Path**: janpoem/inject-jsdom ## Basic Information - **Project Name**: inject-jsdom - **Description**: Inject JSDOM into node.js testing runtime. - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-03-19 - **Last Updated**: 2022-05-25 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # inject-jsdom 为 node.js 的测试环境注入 DOM 全局变量(全局变量加入 `window` `document`)。 这个库的目的旨在在 mocha 环境即可进行 react 的单元测试,无需依赖于 jest。 ## 使用说明 ```shell yarn add inject-jsdom -D pnpm add inject-jsdom -D npm add inject-jsdom --save-dev ``` ### 自动注入 ```ts import 'inject-jsdom/auto'; import { expect } from 'chai'; describe('mocha inject', function () { it('test inject', () => { const newEl = document.createElement('div'); newEl.setAttribute('id', 'test'); newEl.setAttribute('data-value', 'test'); document.body.appendChild(newEl); const el = document.getElementById('test'); expect(el).to.not.eql(null); expect(el?.dataset).to.have.property('value', 'test'); }); }); ``` ### 手动注入 ```ts import { inject } from 'inject-jsdom'; import { expect } from 'chai'; inject({ html : '
', url : 'http://localhost', beforeInject: () => { // ... }, afterInject : (dom) => { // ... } }); describe('mocha inject', function () { it('test inject', () => { const el = document.getElementById('test'); expect(el).to.not.eql(null); expect(el?.dataset).to.have.property('value', 'test'); }); }); ``` ### React 测试 ```tsx import 'inject-jsdom/auto'; import * as React from 'react'; import { render } from 'react-dom'; import { act } from 'react-dom/test-utils'; import { expect } from 'chai'; import { Flex } from './Flex'; let root: HTMLElement; beforeEach(() => { root = document.createElement('div'); document.body.appendChild(root); }); describe('Flex', function () { describe('align items', function () { it('center', () => { act(() => { render(