Skip to content

Commit

Permalink
feat: upgrade Jest to automatically polyfill the testing environment …
Browse files Browse the repository at this point in the history
…in order to use helper libraries for testing web components
  • Loading branch information
sghoweri committed Feb 19, 2019
1 parent 72be039 commit 3eb8345
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 1 deletion.
71 changes: 71 additions & 0 deletions jest-environment-puppeteer-basichtml.js
@@ -0,0 +1,71 @@
const {
CustomElementRegistry,
CustomEvent,
Document,
Event,
Node,
Text,
HTMLElement,
HTMLTemplateElement,
HTMLUnknownElement,
} = require('basichtml');

const NodeEnvironment = require('jest-environment-node');
const fs = require('fs');
const path = require('path');
const puppeteer = require('puppeteer');
const os = require('os');

const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');

class BasicHTMLEnvironment extends NodeEnvironment {
constructor(config) {
super(config);

const window = this.global;

window.customElements = new CustomElementRegistry();
window.document = new Document(window.customElements);
window.document = new Document(window.customElements);
window.HTMLElement = HTMLElement;
window.HTMLUnknownElement = HTMLUnknownElement;
window.Node = Node;
window.Text = Text;
window.window = window;

this.global.navigator = {
userAgent: 'node.js',
};

// Ensure that the real global env has the document
global.document = window.document;
}

async setup() {
await super.setup();
// get the wsEndpoint
const wsEndpoint = fs.readFileSync(path.join(DIR, 'wsEndpoint'), 'utf8');
if (!wsEndpoint) {
throw new Error('wsEndpoint not found');
}

// connect to puppeteer
this.global.__BROWSER__ = await puppeteer.connect({
browserWSEndpoint: wsEndpoint,
});
}

runScript(script) {
return super.runScript(script);
}

async teardown() {
await super.teardown();

this.global.document = null;
this.global.window = null;
global.document = null;
}
}

module.exports = BasicHTMLEnvironment;
2 changes: 1 addition & 1 deletion jest.config.js
Expand Up @@ -17,7 +17,7 @@ module.exports = {
'packages/patternlab-node',
...testFilesToIgnore,
],
testEnvironment: 'node',
testEnvironment: './jest-environment-puppeteer-basichtml.js',
transform: {
'^.+\\.js?$': 'babel-jest',
},
Expand Down
3 changes: 3 additions & 0 deletions package.json
Expand Up @@ -86,6 +86,9 @@
},
"dependencies": {
"babel-jest": "^24.1.0",
"basichtml": "^0.21.1",
"jest-environment-node": "^24.0.0",
"puppeteer": "^1.12.2",
"@zeit/fetch-retry": "^3.0.0",
"ci-utils": "^0.5.0",
"express": "^4.16.4",
Expand Down

0 comments on commit 3eb8345

Please sign in to comment.