From 9caaaf3a91529ed77785aa36c708b8f94a865f82 Mon Sep 17 00:00:00 2001 From: Rob Wu Date: Thu, 6 Jul 2017 11:55:18 +0200 Subject: [PATCH] Add setStubs/unsetStubs to domstubs to support testing Do not directly export to global. Instead, export all stubs in domstubs.js and add a method setStubs to assign all exported stubs to a namespace. Then replace the import domstubs with an explicit call to this setStubs method. Also added unsetStubs for undoing the changes. This is done to allow unit testing of the SVG backend without namespace pollution. --- examples/node/domstubs.js | 25 +++++++++++++++++++++---- examples/node/pdf2svg.js | 2 +- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/examples/node/domstubs.js b/examples/node/domstubs.js index 75b025acd..84b6a0e9c 100644 --- a/examples/node/domstubs.js +++ b/examples/node/domstubs.js @@ -41,7 +41,7 @@ function xmlEncode(s){ return buf; } -global.btoa = function btoa(chars) { +function btoa(chars) { var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var buffer = ''; @@ -57,7 +57,7 @@ global.btoa = function btoa(chars) { digits.charAt(d3) + digits.charAt(d4)); } return buffer; -}; +} function DOMElement(name) { this.nodeName = name; @@ -127,7 +127,7 @@ DOMElement.prototype = { }, } -global.document = { +const document = { childNodes : [], get currentScript() { @@ -171,4 +171,21 @@ Image.prototype = { } } -global.Image = Image; +exports.btoa = btoa; +exports.document = document; +exports.Image = Image; + +var exported_symbols = Object.keys(exports); + +exports.setStubs = function(namespace) { + exported_symbols.forEach(function(key) { + console.assert(!(key in namespace), 'property should not be set: ' + key); + namespace[key] = exports[key]; + }); +}; +exports.unsetStubs = function(namespace) { + exported_symbols.forEach(function(key) { + console.assert(key in namespace, 'property should be set: ' + key); + delete namespace[key]; + }); +}; diff --git a/examples/node/pdf2svg.js b/examples/node/pdf2svg.js index de2b6c56b..f891c9fb6 100644 --- a/examples/node/pdf2svg.js +++ b/examples/node/pdf2svg.js @@ -8,7 +8,7 @@ var fs = require('fs'); // HACK few hacks to let PDF.js be loaded not as a module in global space. -require('./domstubs.js'); +require('./domstubs.js').setStubs(global); // Run `gulp dist-install` to generate 'pdfjs-dist' npm package files. var pdfjsLib = require('pdfjs-dist');