-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
54 lines (46 loc) · 1.76 KB
/
index.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
// Collect client and environment information
const sdkPkg = require('./package.json');
const nightmarePkg = require('nightmare/package.json');
const CLIENT_INFO = `${sdkPkg.name}/${sdkPkg.version}`;
const ENV_INFO = `${nightmarePkg.name}/${nightmarePkg.version}`;
// Take a DOM snapshot and post it to the snapshot endpoint
module.exports = function percySnapshot(name, options) {
if (!name) throw new Error('The `name` argument is required.');
return nightmare => {
let nEval = (fn, ...args) => new Promise((resolve, reject) => {
let done = (err, res) => err ? reject(err) : resolve(res);
nightmare.evaluate_now(fn, done, ...args);
});
nightmare.queue(async done => {
let utils = await import('@percy/sdk-utils');
if (!(await utils.isPercyEnabled())) return done();
let log = utils.logger('nightmare');
try {
// Inject the DOM serialization script
/* eslint-disable-next-line no-new-func */
await nEval(new Function(await utils.fetchPercyDOM()));
// Serialize and capture the DOM
/* istanbul ignore next: no instrumenting injected code */
let { domSnapshot, url } = await nEval(options => ({
/* eslint-disable-next-line no-undef */
domSnapshot: PercyDOM.serialize(options),
url: document.URL
}), options);
// Post the DOM to the snapshot endpoint with snapshot options and other info
await utils.postSnapshot({
...options,
environmentInfo: ENV_INFO,
clientInfo: CLIENT_INFO,
domSnapshot,
url,
name
});
} catch (error) {
// Handle errors
log.error(`Could not take DOM snapshot "${name}"`);
log.error(error);
}
done();
});
};
};