-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
113 lines (97 loc) · 3.24 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
110
111
112
113
import path from 'node:path';
import fastify from 'fastify';
import fastifyStatic from '@fastify/static';
import fastifyBabel from 'fastify-babel';
import {globSync} from 'glob';
export function defaultBabelRC(nodeModulesPrefix, alwaysRootImport = ['**']) {
return {
babelrc: false,
configFile: false,
parserOpts: {
plugins: [
'objectRestSpread',
'importMeta',
'classProperties'
]
},
plugins: [
['babel-plugin-remove-ungap'],
['babel-plugin-bare-import-rewrite', {
alwaysRootImport,
modulesDir: nodeModulesPrefix
}],
['@babel/plugin-transform-optional-chaining', {loose: true}],
['babel-plugin-istanbul']
]
};
}
export function fastifyTestDefaultPlugin(fastify, options, next) {
for (const staticOptions of options.statics) {
fastify.register(fastifyStatic, staticOptions);
}
for (const [url, file] of Object.entries(options.getters || {})) {
fastify.get(url, (_, reply) => reply.sendFile(file));
}
fastify.register(fastifyBabel, {
babelrc: options.babelrc || defaultBabelRC(options.nodeModulesPrefix),
maskError: false
});
next();
}
export class FastifyTestHelper {
_options = {
testsPrefix: '/',
fastifyPlugin: fastifyTestDefaultPlugin,
cwd: process.cwd(),
nodeModulesPrefix: '/node_modules',
extraStatics: []
};
constructor(options = {}) {
options = Object.assign(this._options, options);
if (options.fastifyPlugin === fastifyTestDefaultPlugin && !options.fastifyPluginOpts) {
const decorateReply = false;
const {babelrc, cwd, customGetters, extraStatics, nodeModulesPrefix, nodeModulesRoot, sendFileRoot, testsRoot} = options;
options.fastifyPluginOpts = {
statics: [
{
root: sendFileRoot || cwd,
serve: false
},
{
root: testsRoot || path.resolve(cwd, 'fixtures'),
prefix: this.testsPrefix,
decorateReply
},
{
root: nodeModulesRoot || path.resolve(cwd, 'node_modules'),
prefix: nodeModulesPrefix,
decorateReply
},
...extraStatics
],
getters: customGetters,
nodeModulesPrefix,
babelrc
};
}
}
async start() {
this._daemon = fastify()
.register(this._options.fastifyPlugin, this._options.fastifyPluginOpts);
await this._daemon.listen();
}
async stop() {
this._daemon.server.unref();
}
get baseURL() {
return `http://localhost:${this._daemon.server.address().port}${this._options.testsPrefix}`;
}
}
export function globToCustomGetters(pattern, options) {
const files = globSync(pattern, options);
const result = {};
for (const file of files) {
result[`/${file}`] = file;
}
return result;
}