-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Close #585 PR: Added recipe for writing test with code depending on a…
… window object.
- Loading branch information
1 parent
752ddd3
commit c6214aa
Showing
1 changed file
with
71 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
# Setting up AVA for browser testing | ||
|
||
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). | ||
An example of this is React, at least if you want to use ReactDOM.render and simulate events with ReactTestUtils. | ||
|
||
This recipe works for any library that needs a mocked browser environment. | ||
|
||
## Install jsdom | ||
|
||
Install [jsdom](https://github.com/tmpvar/jsdom). | ||
|
||
> A JavaScript implementation of the WHATWG DOM and HTML standards, for use with node.js | ||
``` | ||
$ npm install --save-dev jsdom | ||
``` | ||
|
||
## Setup jsdom | ||
|
||
Create a helper file and place it in the `test/helpers` folder. This ensures AVA does not treat it as a test. | ||
|
||
`test/helpers/setup-browser-env.js`: | ||
|
||
```js | ||
global.document = require('jsdom').jsdom('<body></body>'); | ||
global.window = document.defaultView; | ||
global.navigator = window.navigator; | ||
``` | ||
|
||
## Configure tests to use jsdom | ||
|
||
Configure AVA to `require` the helper before every test file. | ||
|
||
`package.json`: | ||
|
||
```json | ||
{ | ||
"ava": { | ||
"require": [ | ||
"./test/helpers/setup-browser-env.js" | ||
] | ||
} | ||
} | ||
``` | ||
|
||
## Enjoy! | ||
|
||
Write your tests and enjoy a mocked window object. | ||
|
||
`test/my.react.test.js`: | ||
|
||
```js | ||
import test from 'ava'; | ||
import React from 'react'; | ||
import {render} from 'react-dom'; | ||
import {Simulate} from 'react-addons-test-utils'; | ||
import sinon from 'sinon'; | ||
import CustomInput from './components/custom-input.jsx'; | ||
|
||
test('Input calls onBlur', t => { | ||
const onUserBlur = sinon.spy(); | ||
const input = render( | ||
React.createElement(CustomInput, {onUserBlur), | ||
div | ||
) | ||
|
||
Simulate.blur(input); | ||
|
||
t.true(onUserBlur.calledOnce); | ||
}); | ||
``` |