1.0.1 • Published 6 years ago

min-react-env v1.0.1

Weekly downloads
10
License
Apache-2.0
Repository
github
Last release
6 years ago

min-react-env

minimal browser mocks for testing react-dom code in node.js

It uses min-document with a few tiny addons, mocking just enough for react-dom to be able to run. This is much smaller than using a full JSDOM instance or similar. If you don't do fancy DOM things in your components, min-document could well be enough.

You could just use min-document, but react-dom depends on a few more things to be available on the window object, and this package encapsulates that.

Install - Usage - License: Apache-2.0

npm travis standard

Install

npm install --save-dev min-react-env

Usage

min-react-env exports window and document variables. Assign them to the global object:

import { window, document } from 'min-react-env'
import React from 'react'
import ReactDOM from 'react-dom'

global.window = window
global.document = document

// Assuming a test framework like Mocha or Jest
describe('My Tests', () => {
  const wrapper = document.createElement('main')
  ReactDOM.render(<MyComponent />, wrapper, () => {
    assert.strictEqual(
      wrapper.toString(),
      '<main><div class="MyComponent"></div></main>'
    )
  })
})

Now you can run your react-dom tests in Node!

If you use CommonJS (eg. you don't have a compile step), you can use this pattern:

const test = require('tape')
Object.assign(global, require('min-react-env'))

test('My Tests', (t) => {
  t.plan(1)
  const wrapper = document.createElement('main')
  ReactDOM.render(<MyComponent />, wrapper, () => {
    t.strictEqual(
      wrapper.toString(),
      '<main><div class="MyComponent"></div></main>'
    )
  })
})

The tests for this package actually do something very similar!

License

Apache-2.0