/
index.test.js
210 lines (192 loc) · 6.24 KB
/
index.test.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
const os = require("os");
const fs = require("fs");
const path = require("path");
const { fork } = require("child_process");
const coverage = global.coverage;
const ncc = coverage ? require("../src/index") : require("../");
for (const unitTest of fs.readdirSync(`${__dirname}/unit`)) {
it(`should generate correct output for ${unitTest}`, async () => {
const testDir = `${__dirname}/unit/${unitTest}`;
const expected = fs
.readFileSync(`${testDir}/output${coverage ? '-coverage' : ''}.js`)
.toString()
.trim()
// Windows support
.replace(/\r/g, "");
let expectedSourceMap;
try {
expectedSourceMap = fs
.readFileSync(`${testDir}/output${coverage ? '-coverage' : ''}.js.map`)
.toString()
.trim()
// Windows support
.replace(/\r/g, "");
} catch (_) {}
let opts;
try {
opts = fs.readFileSync(`${testDir}/opt.json`, 'utf8');
opts = JSON.parse(opts);
} catch (_) {}
// set env variable so tsconfig-paths can find the config
process.env.TS_NODE_PROJECT = `${testDir}/tsconfig.json`;
// find the name of the input file (e.g input.ts)
const inputFile = fs.readdirSync(testDir).find(file => file.includes("input"));
await ncc(`${testDir}/${inputFile}`, Object.assign({
transpileOnly: true,
customEmit (path) {
if (path.endsWith('test.json'))
return false;
},
externals: {
'piscina': 'piscina',
'externaltest': 'externalmapped',
'/\\w+-regex/': 'regexexternal',
}
}, opts)).then(
async ({ code, assets, map }) => {
if (unitTest.startsWith('bundle-subasset')) {
expect(assets['pi-bridge.js']).toBeDefined();
expect(assets['pi-bridge.js'].source.toString()).toContain('Math.PI');
}
const actual = code
.trim()
// Windows support
.replace(/\r/g, "")
.replace(/;+/g, ";");
try {
expect(actual).toBe(expected);
} catch (e) {
// useful for updating fixtures
fs.writeFileSync(`${testDir}/actual.js`, actual);
throw e;
}
if (map) {
const actualSourceMap = map
.trim()
// Windows support
.replace(/\r/g, "");
try {
expect(actualSourceMap).toBe(expectedSourceMap);
} catch (e) {
// useful for updating fixtures
fs.writeFileSync(`${testDir}/actual.js.map`, actualSourceMap);
throw e;
}
}
}
)
});
}
for (const cliTest of eval(fs.readFileSync(__dirname + "/cli.js").toString())) {
it(`should execute "ncc ${(cliTest.args || []).join(" ")}"`, async () => {
const ps = fork(__dirname + (coverage ? "/../src/cli.js" : "/../dist/ncc/cli.js"), cliTest.args || [], {
stdio: "pipe",
env: { ...process.env, ...cliTest.env },
});
let stderr = "", stdout = "";
ps.stderr.on("data", chunk => stderr += chunk.toString());
ps.stdout.on("data", chunk => stdout += chunk.toString());
const expected = cliTest.expect || { code: 0 };
let timedOut = false;
if (cliTest.timeout)
setTimeout(() => {
timedOut = true;
ps.kill();
}, cliTest.timeout);
const code = await new Promise(resolve => ps.on("close", resolve));
if (typeof expected === "function")
expect(expected(code, stdout, stderr, timedOut)).toBe(true);
else {
if ("code" in expected)
expect(code).toBe(expected.code);
if ("timeout" in expected)
expect(timedOut).toBe(true);
}
});
}
// the twilio test can take a while (large codebase)
jest.setTimeout(200000);
let nccRun;
if (coverage) {
nccRun = require(__dirname + "/../src/cli.js");
}
else {
nccRun = require(__dirname + "/../dist/ncc/cli.js");
}
const { Writable } = require('stream');
class StoreStream extends Writable {
constructor (options) {
super(options);
this.data = [];
}
_write(chunk, encoding, callback) {
this.data.push(chunk);
callback();
}
}
for (const integrationTest of fs.readdirSync(__dirname + "/integration")) {
// ignore e.g.: `.json` files
if (!/\.(mjs|tsx?|js)$/.test(integrationTest)) continue;
// disabled pending https://github.com/zeit/ncc/issues/141
if (integrationTest.endsWith('loopback.js')) continue;
it(`should execute "ncc run ${integrationTest}"`, async () => {
let expectedStdout;
try {
expectedStdout = fs.readFileSync(`${__dirname}/integration/${integrationTest}.stdout`).toString();
}
catch (e) {}
if (global.gc) global.gc();
const stdout = new StoreStream();
const stderr = new StoreStream();
try {
await nccRun(["run", "--no-cache", "--no-asset-builds", `${__dirname}/integration/${integrationTest}`], stdout, stderr);
}
catch (e) {
if (e.silent) {
let lastErr = stderr.data[stderr.data.length - 1];
if (lastErr)
throw new Error(lastErr);
else
throw new Error('Process exited with code ' + e.exitCode);
}
throw e;
}
if (expectedStdout) {
let stdoutStr = '';
for (const chunk of stdout.data)
stdoutStr += chunk.toString();
expect(stdoutStr.startsWith(expectedStdout));
}
});
}
it(`should execute "ncc build web-vitals" with target config`, async () => {
if (global.gc) global.gc();
const stdout = new StoreStream();
const stderr = new StoreStream();
const tmpOut = path.join(os.tmpdir(), `ncc_${Math.random()}`)
try {
await nccRun(["build", "-o", tmpOut, "--target", "es5", require.resolve('web-vitals/dist/web-vitals.es5.min.js')], stdout, stderr);
}
catch (e) {
if (e.silent) {
let lastErr = stderr.data[stderr.data.length - 1];
if (lastErr)
throw new Error(lastErr);
else
throw new Error('Process exited with code ' + e.exitCode);
}
throw e;
}
const outFile = path.join(tmpOut, 'index.js')
const output = fs.readFileSync(outFile, 'utf8')
// cleanup tmp output
fs.unlinkSync(outFile)
fs.rmdirSync(tmpOut)
expect(output).toContain('function')
// make sure es6 wrapper wasn't used
expect(output).not.toContain('=>')
});
// remove me when node.js makes this the default behavior
process.on("unhandledRejection", e => {
throw e;
});