min-react-env

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

OTHER License

Downloads
245
Stars
3
Committers
1

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

Install

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

Usage

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

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

global.window = window
global.document = document
// Newer versions of Node.js already declare `navigator`
global.navigator ??= navigator

// 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!

There is also a min-react-env/install entry point that assigns all the globals.

const test = require('tape')
require('min-react-env/install')

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

License

Apache-2.0