How to use the jsdom.VirtualConsole function in jsdom

To help you get started, we’ve selected a few jsdom examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mendrik / feather / test / test-head.ts View on Github external
/// 
/// 

const fs = require('fs'),
      jsdom = require('jsdom'),
      sinon = require('sinon'),
      glob = require('glob'),
      path = require('path')

const {JSDOM} = jsdom
const virtualConsole = new jsdom.VirtualConsole()
virtualConsole.sendTo(console, {omitJSDOMErrors: true})

import * as chai from 'chai'

chai.should()
chai.use(require('sinon-chai'))

const mockResponse = (server, url, file) => {
    const ok = [200,  { 'Content-type': 'application/json' }, fs.readFileSync(file, 'utf8')]
    server.respondWith('GET', url, ok)
    server.respondWith('POST', url, ok)
    server.respondWith('DELETE', url, ok)
    server.respondWith('PUT', url, ok)
}

const htmlSource = fs.readFileSync('test/pages/application.html', 'utf8')
github visjs-community / visjs-network / test / canvas-mock.js View on Github external
function mockify(html = '') {
  // Start of message that we want to suppress.
  let msg =
    'Error: Not implemented: HTMLCanvasElement.prototype.getContext' +
    ' (without installing the canvas npm package)'

  // Override default virtual console of jsdom
  const virtualConsole = new jsdom.VirtualConsole()

  // Set up a simple 'mock' console output. Only 'error' needs to be overridden
  let myConsole = {
    error: msg => {
      if (msg.indexOf(msg) === 0) {
        //console.error('all is well');
      } else {
        // All other messages pass through
        console.error(msg)
      }
    }
  }

  // Using the global catch instead of specific event handler, because I couldn't get them to work
  virtualConsole.sendTo(myConsole)
github keplergl / kepler.gl / test / setup-browser-env.js View on Github external
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/* setup.js */
import {JSDOM, VirtualConsole} from 'jsdom';
import global from 'global';

const virtualConsole = new VirtualConsole();
virtualConsole.sendTo(console);

const dom = new JSDOM('', {
  // JSDom 11.12 causes SecurityError: localStorage is not available for opaque origins
  // https://github.com/jsdom/jsdom/issues/2304
  url: 'http://localhost',
  virtualConsole
});
const {window} = dom;
mockCanvas(window);

const nop = () => {};

function mockCanvas(globalWindow) {
  globalWindow.HTMLCanvasElement.prototype.getContext = function mockGetContext() {
    return {
github webhintio / hint / packages / connector-jsdom / src / connector.ts View on Github external
await this.server.emitAsync(`fetch::end::${getType(mediaType!)}` as 'fetch::end::*', fetchEnd);

            /*
             * If the target is not an HTML we don't need to
             * traverse it.
             */
            /* istanbul ignore if */
            if (!isHTMLDocument(this.finalHref, this.headers)) {
                await this.server.emitAsync('scan::end', { resource: this.finalHref });

                resolve();

                return;
            }

            const virtualConsole = new VirtualConsole();

            virtualConsole.on('error', (err: Error) => {
                debug(`Console: ${err}`);
            });

            virtualConsole.on('jsdomError', (err) => {
                debug(`Console: ${err}`);
            });

            const initialDocument = createHTMLDocument(fetchEnd.response.body.content, this.finalHref);

            this._resourceLoader = new CustomResourceLoader(this, initialDocument);

            const jsdom = new JSDOM(this._targetNetworkData.response.body.content, {
                beforeParse: beforeParse(this.finalHref),
                // includeNodeLocations: true, // TODO: re-enable once locations can be copied from snapshot.
github tonickkozlov / vue-tweet-embed / index.spec.jsdom.js View on Github external
return new Promise((resolve, reject) => {
        const dom = new JSDOM('', {
            runScripts: "outside-only",
            // will not log browser events to console
            virtualConsole: new jsdom.VirtualConsole()
        })
        const window = dom.window
        const document = window.document
        const Vue = loadVueIntoWindow(window)

        // require a new instance of Tweet every time to avoid side-effects
        const { Tweet, Moment, Timeline } = require('./dist')

        // window and document needs to be global
        // (required by vue's Ctor.$mount)
        global.window = window
        global.document = document
        resolve({ Vue, Tweet, Moment, Timeline, window, document })
    })
}
github frontarm / navi / packages / navi-scripts / lib / createScriptRunner.js View on Github external
options.onScriptLoaded(url)
                    }
                    
                    return data;
                }
                else {
                    return Buffer.from('')
                    // Let's just ignore any remote files.
                    // return super.fetch(url, fetchOptions);
                }
            }
        }

        let queue = []
        let dom = new jsdom.JSDOM(html, {
            virtualConsole: new jsdom.VirtualConsole().sendTo(console),
            resources: new ResourceLoader(queue),
            runScripts: "dangerously",
            beforeParse(window) {
                // Polyfill rAF for react
                window.requestAnimationFrame = require('raf')
                window.cancelAnimationFrame = require('raf').cancel
                
                // jsdom seems to choke on webpack's  tag loader,
                // so I'm manually calling any onload handlers instead
                // to avoid a deadlock.
                // TODO: get links actually working.
                let appendChild = window.HTMLHeadElement.prototype.appendChild
                window.HTMLHeadElement.prototype.appendChild = function(...args) {
                    let result = appendChild.apply(this, args)
                    if (args[0] instanceof window.HTMLLinkElement && args[0].onload) {
                        if (args[0].rel === "stylesheet" && options.onStyleSheetLoaded) {
github pkra / mathjax-node-page / lib / main.js View on Github external
typesetConfig[jax] = (jax === config.output);
        }
    }

    // generate css for html and svg outputs, if global css option is provided
    if (config.cssInline && (typesetConfig['svg'] || typesetConfig['html'])) {
        typesetConfig['css'] = true;
    }

    // Create jsdom options (cf. defaults for config.jsdom)
    const jsdomConfig = {
        runScripts: config.jsdom.runScript,
    };
    // translate 'true' option
    if (config.jsdom.virtualConsole === true) {
        config.jsdom.virtualConsole = new jsdom.VirtualConsole();
        config.jsdom.virtualConsole.sendTo(console);
    }

    // set up DOM basics
    const doc = typeof input === 'string' ? new JSDOM(input, config.jsdom) : input;
    const window = doc.window;
    const document = window.document;

    //rewrite custom scripts types from core MathJax
    const rewriteScripts = function(oldType, newType) {
        const scripts = document.querySelectorAll('script[type="' + oldType + '"]');
        for (let script of scripts) script.setAttribute('type', newType);
    };
    rewriteScripts('math/tex', 'math/inline-TeX');
    rewriteScripts('math/tex; mode=display', 'math/TeX');
    rewriteScripts('math/asciimath', 'math/asciiMath');
github GoogleChromeLabs / prerender-loader / src / index.js View on Github external
let dom, window, injectParent, injectNextSibling;

  // A promise-like that never resolves and does not retain references to callbacks.
  function BrokenPromise () {}
  BrokenPromise.prototype.then = BrokenPromise.prototype.catch = BrokenPromise.prototype.finally = () => new BrokenPromise();

  if (compilation.assets[compilation.options.output.filename]) {
    // Get the compiled main bundle
    const output = compilation.assets[compilation.options.output.filename].source();

    // @TODO: provide a non-DOM option to allow turning off JSDOM entirely.

    const tpl = options.templateContent || '';
    dom = new jsdom.JSDOM(tpl.replace(PRERENDER_REG, '<div id="PRERENDER_INJECT"></div>'), {
      // suppress console-proxied eval() errors, but keep console proxying
      virtualConsole: new jsdom.VirtualConsole({ omitJSDOMErrors: false }).sendTo(console),

      // `url` sets the value returned by `window.location`, `document.URL`...
      // Useful for routers that depend on the current URL (such as react-router or reach-router)
      url: options.documentUrl || 'http://localhost',

      // don't track source locations for performance reasons
      includeNodeLocations: false,

      // don't allow inline event handlers &amp; script tag exec
      runScripts: 'outside-only'
    });
    window = dom.window;

    // Find the placeholder node for injection &amp; remove it
    const injectPlaceholder = window.document.getElementById('PRERENDER_INJECT');
    if (injectPlaceholder) {
github tbluemel / rtf.js / test / utils.js View on Github external
exports.runEmfjs = function(source, callback, errorCallback) {
    const virtualConsole = new jsdom.VirtualConsole();
    virtualConsole.sendTo(console);

    var dom = new JSDOM(`
    

    
    

    

github e-oj / grabity / utils / index.js View on Github external
/**
 * @author EmmanuelOlaojo
 * @since 11/18/17
 */

let jsdom = require("jsdom");
const {JSDOM} = jsdom;
const virtualConsole = new jsdom.VirtualConsole();

const OG_PROP = "property";
const TWITTER_PROP = "name";
const CONTENT = "content";

virtualConsole.sendTo(console, {omitJSDOMErrors: true});

/**
 * Gets og/twitter title, description, image
 * from a url
 *
 * @param url the url
 *
 * @returns {Promise.&lt;{og: {}, twitter: {}}&gt;}
 */
exports.grabInfo = async (url) =&gt; {