forked from salesforce-ux/design-system
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jest.setup.global.js
99 lines (85 loc) · 2.56 KB
/
jest.setup.global.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
/* eslint-env jest */
import bodyParser from 'body-parser';
import express from 'express';
import path from 'path';
import puppeteer from 'puppeteer';
import { argv } from 'yargs';
// Needed for Jest workers
process.env.JEST_UPDATE_SNAPSHOTS = argv.u === true;
const startServer = port =>
new Promise((resolve, reject) => {
const server = app
.listen(port, () => {
console.log(`server started on port ${port}`);
resolve(server);
})
.on('error', reject);
});
const delay = delay =>
new Promise(resolve => {
setTimeout(resolve, delay);
});
const createPage = async () => {
const page = await browser.newPage();
await page.emulate({
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36',
viewport: {
width: 1280,
height: 800,
deviceScaleFactor: 1,
isMobile: false,
hasTouch: false,
isLandscape: false
}
});
await page.goto(`http://localhost:12345`);
return page;
};
const getMarkupAndStyle = selector => {
const node = document.querySelector(selector);
const nodes = Array.from(node.querySelectorAll('*'));
const extractCSS = n => window.getComputedStyle(n).cssText;
return {
html: node.outerHTML,
style: [extractCSS(node)].concat(nodes.map(extractCSS))
};
};
const app = express();
const pages = [];
let server;
let browser;
app.use('/assets', express.static(path.resolve(__dirname, 'assets')));
app.get('/', (req, res) => {
res.send(`
<!doctype>
<html>
<head>
<link type="text/css" rel="stylesheet" href="/assets/styles/index.css" />
<style type="text/css"
</head>
<body></body>
</html>
`);
});
app.get('/api/jest/teardown', async (req, res) => {
await Promise.all(pages.map(page => page.close()));
await browser.close();
await server.close();
res.sendStatus(200);
});
app.post('/api/getMarkupAndStyle', bodyParser.text(), async (req, res) => {
const page = pages.pop() || (await createPage());
await page.evaluate(html => (document.body.innerHTML = html), req.body);
await delay(200);
const markupAndStyle = await page.evaluate(getMarkupAndStyle, 'body > *');
res.json(markupAndStyle);
pages.push(page);
});
// Jest can't handle exports.default
module.exports = async () => {
server = await startServer(12345);
browser = await puppeteer.launch({ args: ['--no-sandbox'] });
};