Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/goto-bus-stop/min-react-env

minimal browser mocks for testing react-dom code in node.js
https://github.com/goto-bus-stop/min-react-env

browser mock react react-dom testing

Last synced: 27 days ago
JSON representation

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

Awesome Lists containing this project

README

        

# min-react-env

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

It uses [min-document](https://github.com/raynos/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](https://github.com/jsdom/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](#install) - [Usage](#usage) - [License: Apache-2.0](#license)

[![npm][npm-image]][npm-url]
[![travis][travis-image]][travis-url]
[![standard][standard-image]][standard-url]

[npm-image]: https://img.shields.io/npm/v/min-react-env.svg?style=flat-square
[npm-url]: https://www.npmjs.com/package/min-react-env
[travis-image]: https://img.shields.io/travis/com/goto-bus-stop/min-react-env.svg?style=flat-square
[travis-url]: https://travis-ci.com/goto-bus-stop/min-react-env
[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square
[standard-url]: http://npm.im/standard

## Install

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

## Usage

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

```js
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(, wrapper, () => {
assert.strictEqual(
wrapper.toString(),
'

'
)
})
})
```

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.

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

test('My Tests', (t) => {
t.plan(1)
const wrapper = document.createElement('main')
ReactDOM.render(, wrapper, () => {
t.strictEqual(
wrapper.toString(),
'

'
)
})
})
```

## License

[Apache-2.0](LICENSE.md)