/
index.js
109 lines (92 loc) · 2.59 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
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
102
103
104
105
106
107
108
109
const oneLiner = require('one-liner');
const PREFIX = '[ava-test-postcss]';
class PostcssTester {
constructor(opts = {}) {
if (typeof opts.postcss !== 'function') {
throw new Error(
`${PREFIX} You should pass postcss module to PostcssTester`
);
}
this.postcss = opts.postcss;
if (typeof opts.plugin !== 'function' && !Array.isArray(opts.plugin)) {
throw new Error(
`${PREFIX} You should pass your plugin to PostcssTester`
);
}
this.plugins = [];
if (Array.isArray(opts.plugin)) {
for (const plugin of opts.plugin) {
this.plugins.push(plugin);
}
} else {
this.plugins.push(opts.plugin);
}
this.from = typeof opts.from === 'string'
? opts.from
: '';
this.tolerateWarnings = !!opts.tolerateWarnings;
this.exactComparaison = !!opts.exactComparaison;
}
getPlugins(opts = {}) {
const plugins = [];
for (const plugin of opts.pluginsBefore || []) {
plugins.push(plugin);
}
for (const plugin of this.plugins) {
if (typeof opts.pluginOptions !== 'undefined') {
plugins.push(plugin(opts.pluginOptions));
} else {
plugins.push(plugin);
}
}
for (const plugin of opts.pluginsAfter || []) {
plugins.push(plugin);
}
return plugins;
}
async test(input, output, t, opts = {}) {
if (typeof output !== 'function') {
t.plan(1);
}
await this.postcss(this.getPlugins(opts)).process(input, {
from: this.from
}).then(result => {
if (output instanceof Error) {
t.fail(
`${PREFIX} Excepted an error but got a successfull result:`,
result
);
return;
}
const warnings = result.warnings();
if (warnings.length && !this.tolerateWarnings) {
t.fail(`${PREFIX} Some warnings apparead:`, warnings);
return;
}
if (typeof output === 'string') {
if (this.exactComparaison) {
t.is(result.css, output);
} else {
t.is(oneLiner(result.css).trim(), oneLiner(output).trim());
}
return;
}
if (typeof output === 'function') {
output(null, warnings, result.css);
return;
}
t.fail(`${PREFIX} Invalid output type`);
}).catch(err => {
if (typeof output === 'function') {
output(err, null, null);
return;
}
if (!(output instanceof Error)) {
t.fail(`${PREFIX} An unexpected error occured:`, err);
return;
}
t.is(err.message, output.message);
});
}
}
module.exports = PostcssTester;