1.0.0 • Published 2 years ago

inject-jsdom v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

inject-jsdom

为 node.js 的测试环境注入 DOM 全局变量(全局变量加入 window document)。

这个库的目的旨在在 mocha 环境即可进行 react 的单元测试,无需依赖于 jest。

使用说明

yarn add inject-jsdom -D
pnpm add inject-jsdom -D
npm add inject-jsdom --save-dev

自动注入

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');
  });
});

手动注入

import { inject } from 'inject-jsdom';
import { expect } from 'chai';

inject({
  html        : '<html><body><div id="test" data-value="test"></div></body></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');
  });
});