-
Notifications
You must be signed in to change notification settings - Fork 26.1k
/
index.test.js
368 lines (332 loc) · 12.7 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
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
/* eslint-env jest */
import cheerio from 'cheerio'
import { join } from 'path'
import fs from 'fs-extra'
import {
killApp,
findPort,
nextStart,
nextBuild,
renderViaHTTP,
initNextServerScript,
waitFor,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
const fixturesDir = join(__dirname, '..', 'fixtures')
const nodeArgs = [
'-r',
join(__dirname, '../../../lib/react-17-require-hook.js'),
]
const fsExists = (file) =>
fs
.access(file)
.then(() => true)
.catch(() => false)
async function getBuildId(appDir) {
return fs.readFile(join(appDir, '.next', 'BUILD_ID'), 'utf8')
}
const startServerlessEmulator = async (dir, port, opts = {}) => {
const scriptPath = join(dir, 'server.js')
const env = Object.assign(
{},
{ ...process.env },
{ PORT: port, BUILD_ID: await getBuildId(dir) }
)
return initNextServerScript(scriptPath, /ready on/i, env, false, opts)
}
describe('Font Optimization', () => {
describe.each([
[
'google',
[
'https://fonts.googleapis.com/css?family=Voces',
'https://fonts.googleapis.com/css2?family=Modak',
'https://fonts.googleapis.com/css2?family=Roboto:wght@700',
'https://fonts.googleapis.com/css2?family=Roboto:wght@400;700;900&display=swap',
],
[
/<style data-href="https:\/\/fonts\.googleapis\.com\/css\?family=Voces">.*<\/style>/,
/<style data-href="https:\/\/fonts\.googleapis\.com\/css2\?family=Modak">.*<\/style>/,
/<style data-href="https:\/\/fonts\.googleapis\.com\/css2\?family=Roboto:wght@700">.*<\/style>/,
/<style data-href="https:\/\/fonts.googleapis.com\/css2\?family=Roboto:wght@400;700;900&display=swap">.*<\/style>/,
],
'https://fonts.gstatic.com',
],
[
'typekit',
[
'https://use.typekit.net/plm1izr.css',
'https://use.typekit.net/erd0sed.css',
'https://use.typekit.net/ucs7mcf.css',
'https://use.typekit.net/ucs7mcf.css',
],
[
/<style data-href="https:\/\/use.typekit.net\/plm1izr.css">.*<\/style>/,
/<style data-href="https:\/\/use.typekit.net\/erd0sed.css">.*<\/style>/,
/<style data-href="https:\/\/use.typekit.net\/ucs7mcf.css">.*<\/style>/,
/<style data-href="https:\/\/use.typekit.net\/ucs7mcf.css">.*<\/style>/,
],
'https://use.typekit.net',
],
])(
'with-%s',
(
property,
[staticFont, staticHeadFont, starsFont, withFont],
[staticPattern, staticHeadPattern, starsPattern, withFontPattern],
preconnectUrl
) => {
const appDir = join(fixturesDir, `with-${property}`)
const nextConfig = join(appDir, 'next.config.js')
let builtServerPagesDir
let builtPage
let appPort
let app
function runTests() {
it('should pass nonce to the inlined font definition', async () => {
const html = await renderViaHTTP(appPort, '/nonce')
const $ = cheerio.load(html)
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
const link = $(
`link[rel="stylesheet"][data-href="${staticHeadFont}"]`
)
const style = $(`style[data-href="${staticHeadFont}"]`)
const styleNonce = style.attr('nonce')
expect(link.length).toBe(0)
expect(styleNonce).toBe('VmVyY2Vs')
})
it('should only inline included fonts per page', async () => {
const html = await renderViaHTTP(appPort, '/with-font')
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
const $ = cheerio.load(html)
expect($(`link[data-href="${withFont}"]`).length).toBe(0)
expect(html).toMatch(withFontPattern)
const htmlWithoutFont = await renderViaHTTP(appPort, '/without-font')
const $2 = cheerio.load(htmlWithoutFont)
expect($2(`link[data-href="${withFont}"]`).length).toBe(0)
expect(htmlWithoutFont).not.toMatch(withFontPattern)
})
it(`should inline the ${property} fonts for static pages`, async () => {
const html = await renderViaHTTP(appPort, '/index')
const $ = cheerio.load(html)
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect(
$(`link[rel=stylesheet][data-href="${staticFont}"]`).length
).toBe(0)
expect(html).toMatch(staticPattern)
})
it(`should inline the ${property} fonts for static pages with Next/Head`, async () => {
const html = await renderViaHTTP(appPort, '/static-head')
const $ = cheerio.load(html)
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect(
$(`link[rel=stylesheet][data-href="${staticHeadFont}"]`).length
).toBe(0)
expect(html).toMatch(staticHeadPattern)
})
it(`should inline the ${property} fonts for SSR pages`, async () => {
const html = await renderViaHTTP(appPort, '/stars')
const $ = cheerio.load(html)
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect(
$(`link[rel=stylesheet][data-href="${starsFont}"]`).length
).toBe(0)
expect(html).toMatch(starsPattern)
})
it(`should add preconnect tag`, async () => {
const html = await renderViaHTTP(appPort, '/stars')
const $ = cheerio.load(html)
expect(
$(`link[rel=preconnect][href="${preconnectUrl}"]`).length
).toBe(1)
})
it('should skip this optimization for AMP pages', async () => {
const html = await renderViaHTTP(appPort, '/amp')
const $ = cheerio.load(html)
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect($(`link[rel=stylesheet][href="${staticFont}"]`).length).toBe(1)
expect(html).not.toMatch(staticPattern)
})
it('should work for fonts loaded on navigation', async () => {
let browser
try {
browser = await webdriver(appPort, '/')
await waitFor(1000)
const baseFont = await browser.elementByCss(
`style[data-href="${staticFont}"]`
)
expect(baseFont).toBeDefined()
await browser.waitForElementByCss('#with-font')
await browser.click('#with-font')
await browser.waitForElementByCss('#with-font-container')
const pageFontCss = await browser.elementsByCss(
`style[data-href="${withFont}"]`
)
expect(pageFontCss.length).toBe(0)
const pageFont = await browser.elementByCss(
`link[href="${withFont}"]`
)
expect(pageFont).toBeDefined()
} finally {
if (browser) await browser.close()
}
})
it('should minify the css', async () => {
const snapshotJson = JSON.parse(
await fs.readFile(join(appDir, 'manifest-snapshot.json'), {
encoding: 'utf-8',
})
)
const testJson = JSON.parse(
await fs.readFile(builtPage('font-manifest.json'), {
encoding: 'utf-8',
})
)
const normalizeContent = (content) => {
return content.replace(/\/v[\d]{1,}\//g, '/v0/')
}
const testCss = {}
testJson.forEach((fontDefinition) => {
testCss[fontDefinition.url] = normalizeContent(
fontDefinition.content
)
})
const snapshotCss = {}
snapshotJson.forEach((fontDefinition) => {
snapshotCss[fontDefinition.url] = normalizeContent(
fontDefinition.content
)
})
expect(testCss).toStrictEqual(snapshotCss)
})
// Re-run build to check if it works when build is cached
it('should work when build is cached', async () => {
await nextBuild(appDir, undefined, {
nodeArgs,
})
const testJson = JSON.parse(
await fs.readFile(builtPage('font-manifest.json'), {
encoding: 'utf-8',
})
)
expect(testJson.length).toBeGreaterThan(0)
})
}
describe('Font optimization for SSR apps', () => {
beforeAll(async () => {
if (fs.pathExistsSync(join(appDir, '.next'))) {
await fs.remove(join(appDir, '.next'))
}
await nextBuild(appDir, undefined, {
nodeArgs,
})
appPort = await findPort()
app = await nextStart(appDir, appPort, {
nodeArgs,
})
builtServerPagesDir = join(appDir, '.next', 'server')
builtPage = (file) => join(builtServerPagesDir, file)
})
afterAll(() => killApp(app))
runTests()
})
describe('Font optimization for serverless apps', () => {
const origNextConfig = fs.readFileSync(nextConfig)
beforeAll(async () => {
await fs.writeFile(
nextConfig,
`
const path = require('path')
module.exports = require(path.join(__dirname, '../../../../lib/with-react-17.js'))({ target: 'serverless', cleanDistDir: false })
`,
'utf8'
)
await nextBuild(appDir, undefined, {
nodeArgs,
})
appPort = await findPort()
app = await nextStart(appDir, appPort, {
nodeArgs,
})
builtServerPagesDir = join(appDir, '.next', 'serverless')
builtPage = (file) => join(builtServerPagesDir, file)
})
afterAll(async () => {
await fs.writeFile(nextConfig, origNextConfig)
await killApp(app)
})
runTests()
})
describe('Font optimization for emulated serverless apps', () => {
const origNextConfig = fs.readFileSync(nextConfig)
beforeAll(async () => {
await fs.writeFile(
nextConfig,
`
const path = require('path')
module.exports = require(path.join(__dirname, '../../../../lib/with-react-17.js'))({ target: 'experimental-serverless-trace', cleanDistDir: false })
`,
'utf8'
)
await nextBuild(appDir, undefined, {
nodeArgs,
})
appPort = await findPort()
app = await startServerlessEmulator(appDir, appPort, {
nodeArgs,
})
builtServerPagesDir = join(appDir, '.next', 'serverless')
builtPage = (file) => join(builtServerPagesDir, file)
})
afterAll(async () => {
await fs.writeFile(nextConfig, origNextConfig)
await killApp(app)
})
runTests()
})
describe('Font optimization for unreachable font definitions.', () => {
beforeAll(async () => {
await nextBuild(appDir, undefined, {
nodeArgs,
})
await fs.writeFile(
join(appDir, '.next', 'server', 'font-manifest.json'),
'[]',
'utf8'
)
appPort = await findPort()
app = await nextStart(appDir, appPort, {
nodeArgs,
})
builtServerPagesDir = join(appDir, '.next', 'serverless')
builtPage = (file) => join(builtServerPagesDir, file)
})
afterAll(() => killApp(app))
it('should fallback to normal stylesheet if the contents of the fonts are unreachable', async () => {
const html = await renderViaHTTP(appPort, '/stars')
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect(html).toContain(`<link rel="stylesheet" href="${starsFont}"/>`)
})
it('should not inline multiple fallback link tag', async () => {
await renderViaHTTP(appPort, '/stars')
// second render to make sure that the page is requested more than once.
const html = await renderViaHTTP(appPort, '/stars')
expect(await fsExists(builtPage('font-manifest.json'))).toBe(true)
expect(html).not.toContain(
`<link rel="stylesheet" href="${staticFont}"/><link rel="stylesheet" href="${starsFont}"/><link rel="stylesheet" href="${staticFont}"/><link rel="stylesheet" href="${starsFont}"/>`
)
})
})
}
)
test('Spread operator regression on <link>', async () => {
const appDir = join(fixturesDir, 'spread-operator-regression')
const { code } = await nextBuild(appDir)
expect(code).toBe(0)
})
test('makeStylesheetInert regression', async () => {
const appDir = join(fixturesDir, 'make-stylesheet-inert-regression')
const { code } = await nextBuild(appDir)
expect(code).toBe(0)
})
})