forked from meinaart/cypress-plugin-snapshots
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommands.js
101 lines (85 loc) · 2.34 KB
/
commands.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
100
101
/* globals Cypress, before, after, cy */
/* eslint-env browser */
const { merge, cloneDeep } = require('lodash');
const { Base64 } = require('js-base64');
const { MATCH } = require('./tasks/task-names');
const { initUi } = require('./ui');
const {
getTestTitle,
getSnapshotTitle,
} = require('./utils/snapshots');
const {
cleanUpSnapshots,
fixConfig,
getConfig,
getTestForTask,
getSubject,
isHtml,
} = require('./utils/commands');
const {
TYPE_JSON,
TYPE_HTML
} = require('./constants');
const URL_PREFIX = '#cypress-plugin-snapshot-';
const COMMAND_NAME = 'toMatchSnapshot';
const NO_LOG = { log: false };
function commandToMatchSnapshot(testSubject, options) {
const test = getTestForTask();
const testTitle = getTestTitle(test);
const testFile = Cypress.spec.absolute;
const snapshotTitle = getSnapshotTitle(test);
const subject = getSubject(testSubject);
const dataType = isHtml(testSubject) ? TYPE_HTML : TYPE_JSON;
const toMatchSnapshot = (result) => {
const args = Base64.encode(JSON.stringify(result));
const passedMessage = result.expected ? 'Snapshots match' : 'Snapshot created, autopassed';
const message = result.passed ?
`[${passedMessage}](${URL_PREFIX}${args})`
: `[compare snapshot](${URL_PREFIX}${args})`;
const log = Cypress.log({
$el: subject,
name: COMMAND_NAME,
displayName: 'snapshot',
message,
consoleProps: () => result,
});
if (!result.passed) {
log.set('state', 'failed');
throw new Error(`Snapshots do not match:\n${result.diff}`);
}
return subject;
};
return cy.task(MATCH, {
dataType,
options,
snapshotTitle,
subject,
testFile,
testTitle,
}, NO_LOG).then(toMatchSnapshot);
}
function initCommands() {
fixConfig();
// Inject CSS & JavaScript
before(() => {
initUi();
});
// Clean up unused snapshots
after(() => {
cleanUpSnapshots();
});
Cypress.Commands.add(COMMAND_NAME, { prevSubject: 'optional' }, (commandSubject, taskOptions) => {
if (!commandSubject) {
return commandSubject;
}
const options = merge({}, cloneDeep(getConfig()), taskOptions);
return cy.wrap(commandSubject, NO_LOG)
.then((subject) => commandToMatchSnapshot(subject, options));
});
}
module.exports = {
initCommands,
};
if (!process.env.JEST_WORKER_ID) {
initCommands();
}