Skip to content

Commit 2f10448

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

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

docs/recipes/browser-testing.md

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+
```

readme.md

+1
Original file line numberDiff line numberDiff line change
@@ -698,6 +698,7 @@ AVA, not Ava or ava. Pronounced [`/ˈeɪvə/` ay-və](media/pronunciation.m4a?ra
698698
- [Code coverage](docs/recipes/code-coverage.md)
699699
- [Endpoint testing](docs/recipes/endpoint-testing.md)
700700
- [When to use `t.plan()`](docs/recipes/when-to-use-plan.md)
701+
- [Browser testing](docs/recipes/browser-testing.md)
701702

702703

703704
## Support

0 commit comments

Comments
 (0)