Skip to content

Commit 4e4078c

Browse files
0xjockesindresorhus
authored andcommitted
Close #585 PR: Added recipe for writing test with code depending on a window object.
1 parent 752ddd3 commit 4e4078c

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

docs/recipes/browser-testing.md

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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).
4+
Some libraries require browser specific globals (`window`, `document`, `navigator`, etc).
5+
An example of this is React, at least if you want to use ReactDOM.render and simulate events with ReactTestUtils.
6+
7+
This recipe works for any library that needs a mocked browser environment.
8+
9+
## Install jsdom
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+
Create a helper file and place it in the `test/helpers` folder. This ensures AVA does not treat it as a test.
20+
21+
`test/helpers/setup-browser-env.js`:
22+
```js
23+
global.document = require('jsdom').jsdom('<body></body>');
24+
global.window = document.defaultView;
25+
global.navigator = window.navigator;
26+
27+
```
28+
29+
## Configure tests to use jsdom
30+
31+
Configure AVA to `require` the helper before every test file.
32+
33+
`package.json`:
34+
```json
35+
{
36+
"ava": {
37+
"require": [
38+
"./test/helpers/setup-browser-env.js"
39+
]
40+
}
41+
}
42+
```
43+
44+
## Enjoy
45+
46+
Write your tests and enjoy a mocked window object.
47+
48+
`test/my.react.test.js`:
49+
```js
50+
import test from 'ava';
51+
import React from 'react';
52+
import {render} from 'react-dom';
53+
import {Simulate} from 'react-addons-test-utils';
54+
import CustomInput from 'components/custom-input.jsx';
55+
import sinon from 'sinon';
56+
57+
test('Input calls onBlur', t => {
58+
const onUserBlur = sinon.spy();
59+
const input = render(
60+
React.createElement(CustomInput, {onUserBlur),
61+
div,
62+
)
63+
64+
Simulate.blur(input);
65+
66+
t.true(onUserBlur.calledOnce);
67+
})
68+
```

0 commit comments

Comments
 (0)