summaryrefslogtreecommitdiff
path: root/packages/astro/test/content-layer.test.js
blob: 16aa96c2938c27d34f5c66c1fab97111192cbf7d (plain) (blame)
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
import assert from 'node:assert/strict';
import { promises as fs } from 'node:fs';
import { sep } from 'node:path';
import { sep as posixSep } from 'node:path/posix';
import { after, before, describe, it } from 'node:test';
import * as cheerio from 'cheerio';
import * as devalue from 'devalue';

import { loadFixture } from './test-utils.js';
describe('Content Layer', () => {
	/** @type {import("./test-utils.js").Fixture} */
	let fixture;

	before(async () => {
		fixture = await loadFixture({ root: './fixtures/content-layer/' });
	});

	describe('Build', () => {
		let json;
		let $;
		before(async () => {
			fixture = await loadFixture({ root: './fixtures/content-layer/' });
			await fs
				.unlink(new URL('./node_modules/.astro/data-store.json', fixture.config.root))
				.catch(() => {});
			await fixture.build({ force: true });
			const rawJson = await fixture.readFile('/collections.json');
			const html = await fixture.readFile('/spacecraft/lunar-module/index.html');
			$ = cheerio.load(html);
			json = devalue.parse(rawJson);
		});

		it('Returns custom loader collection', async () => {
			assert.ok(json.hasOwnProperty('customLoader'));
			assert.ok(Array.isArray(json.customLoader));

			const item = json.customLoader[0];
			assert.deepEqual(item, {
				id: '1',
				collection: 'blog',
				data: {
					userId: 1,
					id: 1,
					title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
					body: 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto',
				},
			});
		});

		it('filters collection items', async () => {
			assert.ok(json.hasOwnProperty('customLoader'));
			assert.ok(Array.isArray(json.customLoader));
			assert.equal(json.customLoader.length, 5);
		});

		it('Returns json `file()` loader collection', async () => {
			assert.ok(json.hasOwnProperty('jsonLoader'));
			assert.ok(Array.isArray(json.jsonLoader));

			const ids = json.jsonLoader.map((item) => item.data.id);
			assert.deepEqual(ids, [
				'labrador-retriever',
				'german-shepherd',
				'golden-retriever',
				'french-bulldog',
				'bulldog',
				'beagle',
				'poodle',
				'rottweiler',
				'german-shorthaired-pointer',
				'yorkshire-terrier',
				'boxer',
				'dachshund',
				'siberian-husky',
				'great-dane',
				'doberman-pinscher',
				'australian-shepherd',
				'miniature-schnauzer',
				'cavalier-king-charles-spaniel',
				'shih-tzu',
				'boston-terrier',
				'bernese-mountain-dog',
				'pomeranian',
				'havanese',
				'english-springer-spaniel',
				'shetland-sheepdog',
			]);
		});

		it('handles negative matches in glob() loader', async () => {
			assert.ok(json.hasOwnProperty('probes'));
			assert.ok(Array.isArray(json.probes));
			assert.equal(json.probes.length, 5);
			assert.ok(
				json.probes.every(({ id }) => !id.startsWith('voyager')),
				'Voyager probes should not be included',
			);
		});

		it('Returns nested json `file()` loader collection', async () => {
			assert.ok(json.hasOwnProperty('nestedJsonLoader'));
			assert.ok(Array.isArray(json.nestedJsonLoader));

			const ids = json.nestedJsonLoader.map((item) => item.data.id);
			assert.deepEqual(ids, ['bluejay', 'robin', 'sparrow', 'cardinal', 'goldfinch']);
		});

		it('Returns yaml `file()` loader collection', async () => {
			assert.ok(json.hasOwnProperty('yamlLoader'));
			assert.ok(Array.isArray(json.yamlLoader));

			const ids = json.yamlLoader.map((item) => item.id);
			assert.deepEqual(ids, [
				'bubbles',
				'finn',
				'shadow',
				'spark',
				'splash',
				'nemo',
				'angel-fish',
				'gold-stripe',
				'blue-tail',
				'bubble-buddy',
			]);
		});

		it('Returns toml `file()` loader collection', async () => {
			assert.ok(json.hasOwnProperty('tomlLoader'));
			assert.ok(Array.isArray(json.tomlLoader));

			const ids = json.tomlLoader.map((item) => item.data.id);
			assert.deepEqual(ids, [
				'crown',
				'nikes-on-my-feet',
				'stars',
				'never-let-me-down',
				'no-church-in-the-wild',
				'family-ties',
				'somebody',
				'honest',
			]);
		});

		it('Returns nested json `file()` loader collection', async () => {
			assert.ok(json.hasOwnProperty('nestedJsonLoader'));
			assert.ok(Array.isArray(json.nestedJsonLoader));

			const ids = json.nestedJsonLoader.map((item) => item.data.id);
			assert.deepEqual(ids, ['bluejay', 'robin', 'sparrow', 'cardinal', 'goldfinch']);
		});

		it('Returns data entry by id', async () => {
			assert.ok(json.hasOwnProperty('dataEntry'));
			assert.equal(json.dataEntry.filePath?.split(sep).join(posixSep), 'src/data/dogs.json');
			delete json.dataEntry.filePath;
			assert.deepEqual(json.dataEntry, {
				id: 'beagle',
				collection: 'dogs',
				data: {
					breed: 'Beagle',
					id: 'beagle',
					size: 'Small to Medium',
					origin: 'England',
					lifespan: '12-15 years',
					temperament: ['Friendly', 'Curious', 'Merry'],
				},
			});
		});

		it('returns collection from a simple loader', async () => {
			assert.ok(json.hasOwnProperty('simpleLoader'));
			assert.ok(Array.isArray(json.simpleLoader));

			const item = json.simpleLoader[0];
			assert.deepEqual(item, {
				id: 'siamese',
				collection: 'cats',
				data: {
					breed: 'Siamese',
					id: 'siamese',
					size: 'Medium',
					origin: 'Thailand',
					lifespan: '15 years',
					temperament: ['Active', 'Affectionate', 'Social', 'Playful'],
				},
			});
		});

		it('returns a collection from a simple loader that uses an object', async () => {
			assert.ok(json.hasOwnProperty('simpleLoaderObject'));
			assert.ok(Array.isArray(json.simpleLoaderObject));
			assert.deepEqual(json.simpleLoaderObject[0], {
				id: 'capybara',
				collection: 'rodents',
				data: {
					name: 'Capybara',
					scientificName: 'Hydrochoerus hydrochaeris',
					lifespan: 10,
					weight: 50000,
					diet: ['grass', 'aquatic plants', 'bark', 'fruits'],
					nocturnal: false,
				},
			});
		});

		it('transforms a reference id to a reference object', async () => {
			assert.ok(json.hasOwnProperty('entryWithReference'));
			assert.deepEqual(json.entryWithReference.data.cat, { collection: 'cats', id: 'tabby' });
		});

		it('can store Date objects', async () => {
			assert.ok(json.entryWithReference.data.publishedDate instanceof Date);
		});

		it('loads images in frontmatter', async () => {
			assert.ok(json.entryWithReference.data.heroImage.src.startsWith('/_astro'));
			assert.equal(json.entryWithReference.data.heroImage.format, 'jpg');
		});

		it('loads images from custom loaders', async () => {
			assert.ok(json.images[0].data.image.src.startsWith('/_astro'));
			assert.equal(json.images[0].data.image.format, 'jpg');
		});

		it('loads images with absolute paths', async () => {
			assert.ok(json.entryWithImagePath.data.heroImage.src.startsWith('/_astro'));
			assert.equal(json.entryWithImagePath.data.heroImage.format, 'jpg');
		});

		it('handles remote images in custom loaders', async () => {
			assert.ok(json.images[1].data.image.startsWith('https://'));
		});

		it('renders images from frontmatter', async () => {
			assert.ok($('img[alt="Lunar Module"]').attr('src').startsWith('/_astro'));
		});

		it('displays public images unchanged', async () => {
			assert.equal($('img[alt="buzz"]').attr('src'), '/buzz.jpg');
		});

		it('renders local images', async () => {
			assert.ok($('img[alt="shuttle"]').attr('src').startsWith('/_astro'));
		});

		it('returns a referenced entry', async () => {
			assert.ok(json.hasOwnProperty('referencedEntry'));
			assert.deepEqual(json.referencedEntry, {
				collection: 'cats',
				data: {
					breed: 'Tabby',
					id: 'tabby',
					size: 'Medium',
					origin: 'Egypt',
					lifespan: '15 years',
					temperament: ['Curious', 'Playful', 'Independent'],
				},
				id: 'tabby',
			});
		});

		it('allows "slug" as a field', async () => {
			assert.equal(json.increment.data.slug, 'slimy');
		});

		it('updates the store on new builds', async () => {
			assert.equal(json.increment.data.lastValue, 1);
			assert.equal(json.entryWithReference.data.something?.content, 'transform me');
			await fixture.build();
			const newJson = devalue.parse(await fixture.readFile('/collections.json'));
			assert.equal(newJson.increment.data.lastValue, 2);
			assert.equal(newJson.entryWithReference.data.something?.content, 'transform me');
		});

		it('clears the store on new build with force flag', async () => {
			let newJson = devalue.parse(await fixture.readFile('/collections.json'));
			assert.equal(newJson.increment.data.lastValue, 2);
			assert.equal(newJson.entryWithReference.data.something?.content, 'transform me');
			await fixture.build({ force: true }, {});
			newJson = devalue.parse(await fixture.readFile('/collections.json'));
			assert.equal(newJson.increment.data.lastValue, 1);
			assert.equal(newJson.entryWithReference.data.something?.content, 'transform me');
		});

		it('clears the store on new build if the config has changed', async () => {
			let newJson = devalue.parse(await fixture.readFile('/collections.json'));
			assert.equal(newJson.increment.data.lastValue, 1);
			await fixture.editFile('src/content.config.ts', (prev) => {
				return `${prev}\nexport const foo = 'bar';`;
			});
			await fixture.build();
			newJson = devalue.parse(await fixture.readFile('/collections.json'));
			assert.equal(newJson.increment.data.lastValue, 1);
			await fixture.resetAllFiles();
		});
	});

	describe('Dev', () => {
		let devServer;
		let json;
		before(async () => {
			devServer = await fixture.startDevServer({ force: true });
			// Vite may not have noticed the saved data store yet. Wait a little just in case.
			await fixture.onNextDataStoreChange(1000).catch(() => {
				// Ignore timeout, because it may have saved before we get here.
			});
			const rawJsonResponse = await fixture.fetch('/collections.json');
			const rawJson = await rawJsonResponse.text();
			json = devalue.parse(rawJson);
		});

		after(async () => {
			devServer?.stop();
		});

		it('Returns custom loader collection', async () => {
			assert.ok(json.hasOwnProperty('customLoader'));
			assert.ok(Array.isArray(json.customLoader));

			const item = json.customLoader[0];
			assert.deepEqual(item, {
				id: '1',
				collection: 'blog',
				data: {
					userId: 1,
					id: 1,
					title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
					body: 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto',
				},
			});
		});

		it('Returns `file()` loader collection', async () => {
			assert.ok(json.hasOwnProperty('jsonLoader'));
			assert.ok(Array.isArray(json.jsonLoader));

			const ids = json.jsonLoader.map((item) => item.data.id);
			assert.deepEqual(ids, [
				'labrador-retriever',
				'german-shepherd',
				'golden-retriever',
				'french-bulldog',
				'bulldog',
				'beagle',
				'poodle',
				'rottweiler',
				'german-shorthaired-pointer',
				'yorkshire-terrier',
				'boxer',
				'dachshund',
				'siberian-husky',
				'great-dane',
				'doberman-pinscher',
				'australian-shepherd',
				'miniature-schnauzer',
				'cavalier-king-charles-spaniel',
				'shih-tzu',
				'boston-terrier',
				'bernese-mountain-dog',
				'pomeranian',
				'havanese',
				'english-springer-spaniel',
				'shetland-sheepdog',
			]);
		});

		it('Returns data entry by id', async () => {
			assert.ok(json.hasOwnProperty('dataEntry'));
			assert.equal(json.dataEntry.filePath?.split(sep).join(posixSep), 'src/data/dogs.json');
			delete json.dataEntry.filePath;
			assert.deepEqual(json.dataEntry, {
				id: 'beagle',
				collection: 'dogs',
				data: {
					breed: 'Beagle',
					id: 'beagle',
					size: 'Small to Medium',
					origin: 'England',
					lifespan: '12-15 years',
					temperament: ['Friendly', 'Curious', 'Merry'],
				},
			});
		});

		it('reloads data when an integration triggers a content refresh', async () => {
			const rawJsonResponse = await fixture.fetch('/collections.json');
			const initialJson = devalue.parse(await rawJsonResponse.text());
			assert.equal(initialJson.increment.data.lastValue, 1);
			const now = new Date().toISOString();

			const refreshResponse = await fixture.fetch('/_refresh', {
				method: 'POST',
				body: JSON.stringify({ now }),
			});
			const refreshData = await refreshResponse.json();
			assert.equal(refreshData.message, 'Content refreshed successfully');
			const updatedJsonResponse = await fixture.fetch('/collections.json');
			const updated = devalue.parse(await updatedJsonResponse.text());
			assert.equal(updated.increment.data.lastValue, 2);
			assert.deepEqual(updated.increment.data.refreshContextData, { webhookBody: { now } });
		});

		it('updates collection when data file is changed', async () => {
			const rawJsonResponse = await fixture.fetch('/collections.json');
			const initialJson = devalue.parse(await rawJsonResponse.text());
			assert.equal(initialJson.jsonLoader[0].data.temperament.includes('Bouncy'), false);

			await fixture.editFile('/src/data/dogs.json', (prev) => {
				const data = JSON.parse(prev);
				data[0].temperament.push('Bouncy');
				return JSON.stringify(data, null, 2);
			});

			await fixture.onNextDataStoreChange();
			const updatedJsonResponse = await fixture.fetch('/collections.json');
			const updated = devalue.parse(await updatedJsonResponse.text());
			assert.ok(updated.jsonLoader[0].data.temperament.includes('Bouncy'));
			await fixture.resetAllFiles();
		});

		it('returns an error if we render an undefined entry', async () => {
			const res = await fixture.fetch('/missing');
			const text = await res.text();
			assert.equal(res.status, 500);
			assert.ok(text.includes('RenderUndefinedEntryError'));
		});

		it('update the store when a file is renamed', async () => {
			const rawJsonResponse = await fixture.fetch('/collections.json');
			const initialJson = devalue.parse(await rawJsonResponse.text());
			assert.equal(initialJson.numbers.map((e) => e.id).includes('src/data/glob-data/three'), true);

			const oldPath = new URL('./data/glob-data/three.json', fixture.config.srcDir);
			const newPath = new URL('./data/glob-data/four.json', fixture.config.srcDir);

			await fs.rename(oldPath, newPath);
			await fixture.onNextDataStoreChange();

			try {
				const updatedJsonResponse = await fixture.fetch('/collections.json');
				const updated = devalue.parse(await updatedJsonResponse.text());
				assert.equal(updated.numbers.map((e) => e.id).includes('src/data/glob-data/three'), false);
				assert.equal(updated.numbers.map((e) => e.id).includes('src/data/glob-data/four'), true);
			} finally {
				await fs.rename(newPath, oldPath);
			}
		});
	});
});