Skip to content
Permalink
master
Go to file
Out of the box, ESM syntax will only work in Node.js 13, so having that
as the default example is misleading.

Leave it for the TypeScript recipe since TypeScript doesn't work out of
the box anyway. Leave the config example, which will be updated when we
update the config formats for ESM.
10 contributors

Users who have contributed to this file

@forresst @novemberborn @lukechilds @KamuelaFranco @sindresorhus @ptim @silvenon @zhaozhiming @bachstatter @jfmengels
82 lines (55 sloc) 3 KB

Setting up AVA for browser testing

Translations: Español, Français, Italiano, Русский, 简体中文

AVA does not support running tests in browsers yet. However JavaScript libraries that require browser specific globals (window, document, navigator, etc) can still be tested with AVA by mocking these globals.

This recipe works for any library that needs a mocked browser environment.

Install browser-env

❗️ Important note

browser-env adds properties from the jsdom window namespace to the Node.js global namespace. This is explicitly recommended against by jsdom. Please read through the linked wiki page and make sure you understand the caveats. If you don't have lots of dependencies that also require a browser environment then window may be a better solution.

Install browser-env.

Simulates a global browser environment using jsdom.

$ npm install --save-dev browser-env

Setup browser-env

Create a helper file, prefixed with an underscore. This ensures AVA does not treat it as a test.

test/_setup-browser-env.js:

const browserEnv = require('browser-env');
browserEnv();

By default, browser-env will add all global browser variables to the Node.js global scope, creating a full browser environment. This should have good compatibility with most front-end libraries, however, it's generally not a good idea to create lots of global variables if you don't need to. If you know exactly which browser globals you need, you can pass an array of them.

const browserEnv = require('browser-env');
browserEnv(['window', 'document', 'navigator']);

You can expose more global variables by assigning them to the global object. For instance, jQuery is typically available through the $ variable:

const browserEnv = require('browser-env');
const jQuery = require('jquery');

browserEnv();
global.$ = jQuery(window);

Configure tests to use browser-env

Configure AVA to require the helper before every test file.

package.json:

{
	"ava": {
		"require": [
			"./test/_setup-browser-env.js"
		]
	}
}

Enjoy!

Write your tests and enjoy a mocked browser environment.

test.js:

const test = require('ava');

test('Insert to DOM', t => {
	const div = document.createElement('div');
	document.body.appendChild(div);

	t.is(document.querySelector('div'), div);
});
You can’t perform that action at this time.