forked from satya164/jest-file-snapshot
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
74 lines (63 loc) · 2.02 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* istanbul ignore file */
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const diff = require('jest-diff');
exports.toMatchFile = function toMatchFile(content, filename) {
const { isNot, snapshotState } = this;
if (!filename) {
throw new Error('You need to pass a `filename` to `.toMatchFile`.');
}
if (isNot) {
throw new Error('You cannot use `.not` with `.toMatchFile`.');
}
if (snapshotState._updateSnapshot === 'none' && !fs.existsSync(filename)) {
return {
pass: false,
message: () =>
`New output file ${chalk.blue(
path.basename(filename)
)} was ${chalk.bold.red(
'not written'
)}. The update flag must be explicitly ` +
'passed to write a new snapshot.\n\n + This is likely because this test is run in a continuous ' +
'integration (CI) environment in which snapshots are not written by default.\n\n',
};
}
if (fs.existsSync(filename)) {
const output = fs.readFileSync(filename, 'utf8');
if (output === content) {
return { pass: true, message: () => '' };
} else {
if (snapshotState._updateSnapshot === 'all') {
fs.writeFileSync(filename, content);
snapshotState.updated++;
return { pass: true, message: () => '' };
} else {
snapshotState.unmatched++;
return {
pass: false,
message: () =>
`${chalk.red('Received content')} doesn't match ${chalk.green(
path.basename(filename)
)}.\n\n${diff(content, output)}`,
};
}
}
} else {
if (snapshotState._updateSnapshot === 'all') {
fs.writeFileSync(filename, content);
snapshotState.added++;
return { pass: true, message: () => '' };
} else {
snapshotState.unmatched++;
return {
pass: false,
message: () =>
`The output file ${chalk.blue(
path.basename(filename)
)} ${chalk.bold.red("doesn't exist")}.`,
};
}
}
};