|
| 1 | +# Setting up AVA for browser testing |
| 2 | + |
| 3 | +AVA does not support running tests in browsers [yet](https://github.com/sindresorhus/ava/issues/24). Some libraries require browser specific globals (`window`, `document`, `navigator`, etc). |
| 4 | +An example of this is React, at least if you want to use ReactDOM.render and simulate events with ReactTestUtils. |
| 5 | + |
| 6 | +This recipe works for any library that needs a mocked browser environment. |
| 7 | + |
| 8 | +## Install jsdom |
| 9 | + |
| 10 | +Install [jsdom](https://github.com/tmpvar/jsdom). |
| 11 | + |
| 12 | +> A JavaScript implementation of the WHATWG DOM and HTML standards, for use with node.js |
| 13 | +
|
| 14 | +``` |
| 15 | +$ npm install --save-dev jsdom |
| 16 | +``` |
| 17 | + |
| 18 | +## Setup jsdom |
| 19 | + |
| 20 | +Create a helper file and place it in the `test/helpers` folder. This ensures AVA does not treat it as a test. |
| 21 | + |
| 22 | +`test/helpers/setup-browser-env.js`: |
| 23 | + |
| 24 | +```js |
| 25 | +global.document = require('jsdom').jsdom('<body></body>'); |
| 26 | +global.window = document.defaultView; |
| 27 | +global.navigator = window.navigator; |
| 28 | +``` |
| 29 | + |
| 30 | +## Configure tests to use jsdom |
| 31 | + |
| 32 | +Configure AVA to `require` the helper before every test file. |
| 33 | + |
| 34 | +`package.json`: |
| 35 | + |
| 36 | +```json |
| 37 | +{ |
| 38 | + "ava": { |
| 39 | + "require": [ |
| 40 | + "./test/helpers/setup-browser-env.js" |
| 41 | + ] |
| 42 | + } |
| 43 | +} |
| 44 | +``` |
| 45 | + |
| 46 | +## Enjoy! |
| 47 | + |
| 48 | +Write your tests and enjoy a mocked window object. |
| 49 | + |
| 50 | +`test/my.react.test.js`: |
| 51 | + |
| 52 | +```js |
| 53 | +import test from 'ava'; |
| 54 | +import React from 'react'; |
| 55 | +import {render} from 'react-dom'; |
| 56 | +import {Simulate} from 'react-addons-test-utils'; |
| 57 | +import sinon from 'sinon'; |
| 58 | +import CustomInput from './components/custom-input.jsx'; |
| 59 | + |
| 60 | +test('Input calls onBlur', t => { |
| 61 | + const onUserBlur = sinon.spy(); |
| 62 | + const input = render( |
| 63 | + React.createElement(CustomInput, {onUserBlur), |
| 64 | + div |
| 65 | + ) |
| 66 | + |
| 67 | + Simulate.blur(input); |
| 68 | + |
| 69 | + t.true(onUserBlur.calledOnce); |
| 70 | +}); |
| 71 | +``` |
0 commit comments