How to use jsdom - 10 common examples

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 sysgears / apollo-universal-starter-kit / modules / testing / client-react / Renderer.tsx View on Github external
import { addTypenameToDocument } from 'apollo-utilities';
import { Router, Switch } from 'react-router-dom';
import { createMemoryHistory, MemoryHistory } from 'history';
import { JSDOM } from 'jsdom';
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import { combineReducers, createStore, Store } from 'redux';
import { graphql, print, getOperationAST, DocumentNode, GraphQLSchema } from 'graphql';
import { Provider } from 'react-redux';
import { ApolloClient } from 'apollo-client';
import { render, RenderResult } from '@testing-library/react';

import { createApolloClient } from '@gqlapp/core-common';
import ClientModule from '@gqlapp/module-client-react';

if (!process.env.JEST_WORKER_ID) {
  const dom = new JSDOM('<div id="root"><div>');
  (global as any).document = dom.window.document;
  (global as any).window = dom.window;
  // Needed by Formik &gt;= 1.x
  (global as any).HTMLButtonElement = dom.window.HTMLButtonElement;
  (global as any).navigator = dom.window.navigator;
  process.on('uncaughtException', ex =&gt; {
    console.error('Uncaught error', ex.stack);
  });
}

const ref: { clientModules: ClientModule; typeDefs: DocumentNode[] } = { clientModules: null, typeDefs: null };

export const initRenderer = (graphqlTypeDefs: DocumentNode[], clientModules: ClientModule) =&gt; {
  ref.clientModules = clientModules;
  ref.typeDefs = graphqlTypeDefs;
};</div></div>
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) =&gt; {
    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 codeschool-projects / jQueryBadgesProject / test / badges.spec.js View on Github external
const mockData = require('./response.mock');
const sinon = require('sinon');
const srcScript = fs.readFileSync('./src/assets/main.js', 'utf8');

const scriptRegex = /&lt;\s*script[\s\S]*?&gt;[\s\S]*?&lt;\s*\/\s*script\s*&gt;/ig;
const codeschoolRegex = /https:\/\/www\.codeschool\.com\/users\/.+\.json/i;

// HTML Page
let srcHtml = fs.readFileSync('./src/index.html', 'utf8');
srcHtml = srcHtml.replace(
  scriptRegex,
  (tag) =&gt; !/src\s*=['"][^'"]*assets\//i.test(tag) ? tag : ''
);

// JSDOM Setup
const virtualConsole = jsdom.createVirtualConsole();
virtualConsole.sendTo(console);

// Tests
describe('The webpage', () =&gt; {

  let document;
  let window;
  let spy;

  before((done) =&gt; {

    document = jsdom.jsdom(srcHtml, {
      virtualConsole: virtualConsole,
    });

    window = document.defaultView;
github FamilySearch / fs-js-lite / test / browser.js View on Github external
function createClient(envConfig, clientConfig, callback){
    clientConfig = Object.assign({
      appKey: sandbox.appkey
    }, clientConfig || {});
    envConfig = Object.assign({
      html: '<div></div>',
      scripts: 'file://' + __dirname + '/../dist/FamilySearch.min.js',
      /* Enable the virtual console to pipe the virtual window console
         into the console of the current node instance. Helpful for debugging tests. */
      virtualConsole: jsdom.createVirtualConsole().sendTo(console),
      done: function(error, window){
        if(error){
          console.error(error);
          callback(error);
        }
        else {
          callback(null, new window.FamilySearch(clientConfig));
        }
      }
    }, envConfig || {});
    jsdom.env(envConfig);
  }
github edrlab / webpub-viewer / test / IFrameNavigatorTests.ts View on Github external
it("should go to next page", async () => {
            jsdom.changeURL(window, "http://example.com");
            const chapterPosition = element.querySelector(".chapter-position") as HTMLSpanElement;
            
            const iframe = element.querySelector("iframe") as HTMLIFrameElement;
            paginatorCurrentPage = 4;

            // If you're not on the last page, it goes to the next page.
            eventHandler.onRightTap(new UIEvent("mouseup"));
            expect(onLastPage.callCount).to.equal(1);
            expect(goToNextPage.callCount).to.equal(1);
            expect(chapterPosition.innerHTML).to.equal("Page 4 of 8");

            await pause();
            expect(saveLastReadingPosition.callCount).to.equal(2);
            expect(saveLastReadingPosition.args[1][0]).to.deep.equal({
                resource: "http://example.com/start.html",
                position: 0.25
github joseluisq / prelodr / test / prelodr.spec.js View on Github external
test('Prelodr jQuery', t =&gt; {
  jsdom.env('', [
    require.resolve('../bower_components/jquery/dist/jquery.js')
  ], (err, window) =&gt; {
    /* istanbul ignore if */
    if (err) {
      return;
    }

    const $ = window.jQuery;

    global.window = window;
    global.document = window.document;

    $.fn.prelodr = function (options) {
      let fn;
      let prelodr;
github attodorov / blast.js / test / blast-core.js View on Github external
var jsdom = require("jsdom");
var assert = require("chai").assert;
var expect = require("chai").expect;
var should = require("chai").should();
var chai = require("chai");
var requirejs = require("requirejs");
//chai.config.includeStack = true;

requirejs.config({
        nodeRequire: require,
        baseUrl: "./src/"
});

//var fs = require("fs");
//var html = fs.readFileSync("test/template.html", "utf8");
jsdom.defaultDocumentFeatures = { 
	FetchExternalResources   : ["script"],
	ProcessExternalResources : ["script"],
	MutationEvents           : "2.0",
  	QuerySelector            : true
};
// load our sample and we'll test core functionality on it, no need to develop that stuff again
var window, doc, donefn, started = false, blast;
doc = jsdom.jsdom("");
window = doc.parentWindow;
GLOBAL.window = window;
GLOBAL.document = doc;
blast = requirejs("blast");
window.addEventListener("load", function () {
	if (donefn) {
		donefn(); // start tests
	}
github rummelj / bindingjs / tst / integration / testrunner.js View on Github external
it("should execute all testcases", (done) => {
        var jsdom = require("jsdom")
        jsdom.defaultDocumentFeatures = {
            FetchExternalResources   : ["script"],
            ProcessExternalResources : ["script"],
            MutationEvents           : true,
            QuerySelector            : true
        };

        var fs = require("fs")
        
        /* Gets all sub directories in dir */
        var getDirectories = (fs, dir) => {
            var files = fs.readdirSync(dir)
            var result = []
            files.forEach((file) => {
                var stat = fs.statSync(dir + "/" + file)
                if (stat.isDirectory()){
                    result.push(file)
github vecnatechnologies / backbone-torso / test / spec / functional / clientEnv.js View on Github external
done: function(error, window) {
        if (argv.v) {
          jsdom.getVirtualConsole(window).sendTo(console);
        }

        if (error) {
          console.log("Error loading functional testing environment: ");
          console.log(error);
          console.log();
          reject(error)
        }

        // TODO add handlebarsUtils import function to window/ on torso. then here, add handlebars from window to handlebarsUtils
        window.Torso.Utils.handlebarsUtils(window.Handlebars);
        // This sync is needed because TestView.js imports a compiled .hbs file outside of the window's scope so it uses a different
        // Set of handlebars helpers.
        window._.each(window.Handlebars.helpers, function(helperFunction, helperName) {
          handlebars.registerHelper(helperName, helperFunction);
        });