Skip to content

Instantly share code, notes, and snippets.

@senica
Created June 30, 2017 17:38
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save senica/cf5cec2ce54f18025d43d63e26acf50c to your computer and use it in GitHub Desktop.
JSDOM simplification for loading scripts
/**
* If you are use to pre-version 10 jsdom, post 10 is an absolute nuisance for loading scripts...especially when you just
* want to test some code.
* This just creates a nice little wrapper to simplify everythign.
**/
const __jsdom = require("jsdom");
const { JSDOM } = __jsdom;
global.jsdom = function(html = '', scripts = []){
return new Promise((resolve, reject)=>{
try{
let _scripts = [];
for(let script of scripts){
_scripts.push(`<script src="${script}"></script>`)
}
let dom = new JSDOM(`<body>
${html}
${_scripts.join('\n')}
</body>`, {
resources: 'usable',
runScripts: 'dangerously'
});
dom.window.addEventListener('load', ()=>{
resolve(dom);
})
}catch(e){
reject(e);
}
});
}
@senica
Copy link
Author

senica commented Jun 30, 2017

/**
 * Usage:
 * calling jsdom will return a promise.
 * When the window is loaded, it will resolve the promise.
 * First parameter is your html.
 * Second parameter is an array of scripts you want to load.
 * Not a whole lot of magic to it.
 */
it('verifies browser connection to socket server', async (done)=>{
    try{
      let dom = await jsdom(`<div>Some more html here</div>`, ['http://localhost/js/somejs.js'])
      assert(false, true)
      done();
    }catch(e){
      done(e);
    }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment