forked from markdoc/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.test.js
252 lines (209 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
const vm = require('vm');
const fs = require('fs');
const path = require('path');
const babel = require('@babel/core');
const React = require('react');
const enhancedResolve = require('enhanced-resolve');
const loader = require('../src/loader');
const source = fs.readFileSync(require.resolve('./fixture.md'), 'utf-8');
// https://stackoverflow.com/questions/53799385/how-can-i-convert-a-windows-path-to-posix-path-using-node-path
function normalizeAbsolutePath(s) {
return s
.replace(/^[a-zA-Z]:/, '') // replace C: for Windows
.split(path.sep)
.join(path.posix.sep);
}
function normalizeOperatingSystemPaths(s) {
return s
.replace(normalizeAbsolutePath(process.cwd()), '.')
.split(path.sep)
.join(path.posix.sep)
.replace(/\/r\/n/g, '\\n');
}
function evaluate(output) {
const {code} = babel.transformSync(output);
const exports = {};
// https://stackoverflow.com/questions/38332094/how-can-i-mock-webpacks-require-context-in-jest
require.context = require.context = (base = '.') => {
const files = [];
function readDirectory(directory) {
fs.readdirSync(directory).forEach((file) => {
const fullPath = path.resolve(directory, file);
if (fs.statSync(fullPath).isDirectory()) {
readDirectory(fullPath);
}
files.push(fullPath);
});
}
readDirectory(path.resolve(__dirname, base));
return Object.assign(require, {keys: () => files});
};
vm.runInNewContext(code, {
exports,
require,
console,
});
return exports;
}
function options(config = {}) {
const webpackThis = {
context: __dirname,
getOptions() {
return {
...config,
dir: __dirname,
nextRuntime: 'nodejs',
};
},
getLogger() {
return console;
},
addDependency() {},
addContextDependency() {},
getResolve: (options) => {
const resolve = enhancedResolve.create(options);
return async (context, file) =>
new Promise((res, rej) =>
resolve(context, file, (err, result) =>
err ? rej(err) : res(result)
)
).then(normalizeAbsolutePath);
},
resourcePath: '/Users/someone/a-next-js-repo/pages/test/index.md',
};
return webpackThis;
}
async function callLoader(config, source) {
return new Promise((res, rej) => {
config.async = () => (error, result) => {
if (error) {
rej(error);
} else {
res(result);
}
};
loader.call(config, source);
});
}
test('should not fail build if default `schemaPath` is used', async () => {
await expect(callLoader(options(), source)).resolves.toEqual(
expect.any(String)
);
});
test('should fail build if invalid `schemaPath` is used', async () => {
await expect(
callLoader(options({schemaPath: 'unknown_schema_path'}), source)
).rejects.toThrow("Cannot find module 'unknown_schema_path'");
});
test('file output is correct', async () => {
const output = await callLoader(options(), source);
expect(normalizeOperatingSystemPaths(output)).toMatchSnapshot();
const page = evaluate(output);
expect(evaluate(output)).toEqual({
default: expect.any(Function),
getStaticProps: expect.any(Function),
});
const data = await page.getStaticProps({});
expect(data.props.markdoc).toEqual({
content: {
$$mdtype: 'Tag',
name: 'article',
attributes: {},
children: [
{
$$mdtype: 'Tag',
name: 'h1',
attributes: {},
children: ['Custom title'],
},
],
},
frontmatter: {
title: 'Custom title',
},
file: {
path: '/test/index.md',
},
});
expect(page.default(data.props)).toEqual(
React.createElement(
'article',
undefined,
React.createElement('h1', undefined, 'Custom title')
)
);
});
test('app router', async () => {
const output = await callLoader(options({ appDir: true }), source);
expect(normalizeOperatingSystemPaths(output)).toMatchSnapshot();
const page = evaluate(output);
expect(evaluate(output)).toEqual({
default: expect.any(Function),
});
expect(await page.default({})).toEqual(
React.createElement(
'article',
undefined,
React.createElement('h1', undefined, 'Custom title')
)
);
});
test('app router metadata', async () => {
const output = await callLoader(
options({ appDir: true }),
source.replace('---', '---\nmetadata:\n title: Metadata title')
);
expect(output).toContain('export const metadata = frontmatter.nextjs?.metadata;')
});
test.each([
[undefined, undefined],
['./schemas/folders', 'markdoc1'],
['./schemas/folders/', 'markdoc1'],
['./schemas/files', 'markdoc2'],
['schemas/files', 'markdoc2'],
['schemas/typescript', source],
])('Custom schema path ("%s")', async (schemaPath, expectedChild) => {
const output = await callLoader(options({schemaPath}), source);
const page = evaluate(output);
const data = await page.getStaticProps({});
expect(data.props.markdoc.content.children[0].children[0]).toEqual(
'Custom title'
);
expect(data.props.markdoc.content.children[1]).toEqual(expectedChild);
});
test('Partials', async () => {
const output = await callLoader(
options({schemaPath: './schemas/partials'}),
`${source}\n{% partial file="footer.md" /%}`
);
const page = evaluate(output);
const data = await page.getStaticProps({});
expect(data.props.markdoc.content.children[1].children[0]).toEqual('footer');
});
test('Ejected config', async () => {
const output = await callLoader(
options({schemaPath: './schemas/ejectedConfig'}),
`${source}\n{% $product %}`
);
const page = evaluate(output);
const data = await page.getStaticProps({});
expect(data.props.markdoc.content.children[1]).toEqual('Extra value');
expect(data.props.markdoc.content.children[2].children[0]).toEqual('meal');
});
test('HMR', async () => {
const output = await callLoader(
{
...options(),
hot: true,
},
source
);
expect(normalizeOperatingSystemPaths(output)).toMatchSnapshot();
});
test('mode="server"', async () => {
const output = await callLoader(options({mode: 'server'}), source);
expect(evaluate(output)).toEqual({
default: expect.any(Function),
getServerSideProps: expect.any(Function),
});
});