From d95f15531bdff95988e24677cf1403b20c482db3 Mon Sep 17 00:00:00 2001 From: Luke Childs Date: Wed, 22 Mar 2017 09:59:41 +0800 Subject: [PATCH] Document universal testing pattern --- README.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/README.md b/README.md index 98b467e..1f6642d 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,35 @@ document.body.querySelector('.foo').textContent; // "Hi!" ``` +## Universal Testing Pattern + +You can use a really simple pattern to enable your browser modules to run in Node.js with `window`. Just allow a window object to be passed in to your module and prepend any references to browser globals with `win`. Set `win` to the passed in window object if it exists, otherwise fallback to global `window`. + +```js +module.exports = function(text, win) { + win = win || window; + + win.document.body.innerHTML = `

${text}

`; + return window.document.querySelector('h1'); +}; +``` + +Browser usage: + +```js +module('Hi'); +//

Hi

+``` + +Node.js usage: + +```js +module('Hi', new Window()); +//

Hi

+``` + + + ## License MIT © Luke Childs