Unverified Commit 092346d3 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

test: clean up duplicated tests (#36871)

Clean up integration tests

* app-document: Merge multi fetch reuqests into 1, add checking for `__NEXT_DATA__`
* rsc/streaming: Merge duplicated tests, move the head tests to client-navigation since they're running under react 18 now
* remove runtime subtest suite under rsc tests since it's covered in switchable runtime test suite
parent d67baa0d
...@@ -12,14 +12,18 @@ export default function ({ app }, suiteName, render, fetch) { ...@@ -12,14 +12,18 @@ export default function ({ app }, suiteName, render, fetch) {
describe(suiteName, () => { describe(suiteName, () => {
describe('_document', () => { describe('_document', () => {
test('It has a custom html class', async () => { test('should include required elements in rendered html', async () => {
const $ = await get$('/') const $ = await get$('/')
// It has a custom html class
expect($('html').hasClass('test-html-props')).toBe(true) expect($('html').hasClass('test-html-props')).toBe(true)
}) // It has a custom body class
test('It has a custom body class', async () => {
const $ = await get$('/')
expect($('body').hasClass('custom_class')).toBe(true) expect($('body').hasClass('custom_class')).toBe(true)
// It injects custom head tags
expect($('head').text()).toMatch('body { margin: 0 }')
// It has __NEXT_DATA__ script tag
expect($('script#__NEXT_DATA__')).toBeTruthy()
// It passes props from Document.getInitialProps to Document
expect($('#custom-property').text()).toBe('Hello Document')
}) })
it('Document.getInitialProps returns html prop representing app shell', async () => { it('Document.getInitialProps returns html prop representing app shell', async () => {
...@@ -30,16 +34,6 @@ export default function ({ app }, suiteName, render, fetch) { ...@@ -30,16 +34,6 @@ export default function ({ app }, suiteName, render, fetch) {
expect($about('#css-in-cjs-count').text()).toBe('0') expect($about('#css-in-cjs-count').text()).toBe('0')
}) })
test('It injects custom head tags', async () => {
const $ = await get$('/')
expect($('head').text()).toMatch('body { margin: 0 }')
})
test('It passes props from Document.getInitialProps to Document', async () => {
const $ = await get$('/')
expect($('#custom-property').text()).toBe('Hello Document')
})
test('It adds nonces to all scripts and preload links', async () => { test('It adds nonces to all scripts and preload links', async () => {
const $ = await get$('/') const $ = await get$('/')
const nonce = 'test-nonce' const nonce = 'test-nonce'
......
...@@ -1438,6 +1438,82 @@ describe('Client Navigation', () => { ...@@ -1438,6 +1438,82 @@ describe('Client Navigation', () => {
} }
}) })
it('should warn when stylesheets or scripts are in head', async () => {
let browser
try {
browser = await webdriver(context.appPort, '/head')
await browser.waitForElementByCss('h1')
await waitFor(1000)
const browserLogs = await browser.log('browser')
let foundStyles = false
let foundScripts = false
const logs = []
browserLogs.forEach(({ message }) => {
if (message.includes('Do not add stylesheets using next/head')) {
foundStyles = true
logs.push(message)
}
if (message.includes('Do not add <script> tags using next/head')) {
foundScripts = true
logs.push(message)
}
})
expect(foundStyles).toEqual(true)
expect(foundScripts).toEqual(true)
// Warnings are unique
expect(logs.length).toEqual(new Set(logs).size)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should warn when scripts are in head', async () => {
let browser
try {
browser = await webdriver(context.appPort, '/head')
await browser.waitForElementByCss('h1')
await waitFor(1000)
const browserLogs = await browser.log('browser')
let found = false
browserLogs.forEach((log) => {
if (log.message.includes('Use next/script instead')) {
found = true
}
})
expect(found).toEqual(true)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should not warn when application/ld+json scripts are in head', async () => {
let browser
try {
browser = await webdriver(context.appPort, '/head-with-json-ld-snippet')
await browser.waitForElementByCss('h1')
await waitFor(1000)
const browserLogs = await browser.log('browser')
let found = false
browserLogs.forEach((log) => {
if (log.message.includes('Use next/script instead')) {
found = true
}
})
expect(found).toEqual(false)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should update head during client routing', async () => { it('should update head during client routing', async () => {
let browser let browser
try { try {
......
import React from 'react'
import Head from 'next/head'
export default () => (
<div>
<Head>
<link rel="stylesheet" href="style-a.css" key="my-style" />
<link rel="stylesheet" href="style-b.css" key="my-style" />
<script src="/test-async.js" async></script>
<script src="/test-defer.js" defer="yas"></script>
</Head>
<h1>Streaming Head</h1>
</div>
)
export default function () {
return process.version
? `Runtime: Node.js ${process.version}`
: 'Runtime: Edge/Browser'
}
export const config = {
runtime: 'nodejs',
}
export default function () {
return process.env.NEXT_RUNTIME === 'nodejs'
? `Runtime: Node.js ${process.version}`
: 'Runtime: Edge/Browser'
}
export const config = {
runtime: 'nodejs',
}
import webdriver from 'next-webdriver'
import { renderViaHTTP } from 'next-test-utils' import { renderViaHTTP } from 'next-test-utils'
export default async function basic(context, { env }) { export default async function basic(context, { env }) {
it('should render 404 error correctly', async () => {
const path404HTML = await renderViaHTTP(context.appPort, '/404')
const pathNotFoundHTML = await renderViaHTTP(context.appPort, '/not-found')
expect(path404HTML).toContain('custom-404-page')
expect(pathNotFoundHTML).toContain('custom-404-page')
})
it('should render title correctly', async () => {
const res = await renderViaHTTP(context.appPort, '/')
expect(res).toContain('<title>hello, env_var_test</title>')
})
it('should support api routes', async () => {
const res = await renderViaHTTP(context.appPort, '/api/ping')
expect(res).toContain('pong')
})
it('should handle suspense error page correctly (node stream)', async () => {
const browser = await webdriver(context.appPort, '/404')
const hydrationContent = await browser.waitForElementByCss('#__next').text()
expect(hydrationContent).toBe('custom-404-pagenext_streaming_data')
})
it('should render 500 error correctly', async () => { it('should render 500 error correctly', async () => {
const errPaths = ['/err', '/err/render'] const errPaths = ['/err', '/err/render']
const promises = errPaths.map(async (pagePath) => { const promises = errPaths.map(async (pagePath) => {
...@@ -45,22 +19,4 @@ export default async function basic(context, { env }) { ...@@ -45,22 +19,4 @@ export default async function basic(context, { env }) {
const html = await renderViaHTTP(context.appPort, '/err/suspense') const html = await renderViaHTTP(context.appPort, '/err/suspense')
expect(html).toContain('error-fallback') expect(html).toContain('error-fallback')
}) })
it('should support React.lazy and dynamic imports', async () => {
const html = await renderViaHTTP(context.appPort, '/dynamic-imports')
expect(html).toContain('foo.client')
const browser = await webdriver(context.appPort, '/dynamic-imports')
const content = await browser.eval(`window.document.body.innerText`)
const dynamicIds = await browser.eval(`__NEXT_DATA__.dynamicIds`)
expect(content).toMatchInlineSnapshot('"foo.clientbar.client"')
expect(dynamicIds).toBe(undefined)
})
if (env === 'prod') {
it(`should not display custom _app or _app.server in treeview if there's not any`, () => {
const { stdout } = context
expect(stdout).not.toMatch(/\s\/_app(\.server)?/)
})
}
} }
/**
* This test contains everything related to edge and lambda functions such as
* functions-manifest.
*/
import fs from 'fs-extra'
import { join } from 'path'
import { nextBuild } from './utils'
export default function (context) {
it('should not generate functions manifest when filesystem API is not enabled', async () => {
// Make sure there is no existing functions manifest (caused by failed tests etc).
const distDir = join(context.appDir, '.next')
await fs.remove(distDir)
await nextBuild(context.appDir)
const functionsManifestPath = join(
distDir,
'server',
'functions-manifest.json'
)
expect(fs.existsSync(functionsManifestPath)).toBe(false)
await fs.remove(join(context.appDir, '.next'))
})
it('should contain rsc paths in functions manifest', async () => {
const distDir = join(context.appDir, '.next')
await nextBuild(context.appDir, { env: { ENABLE_FILE_SYSTEM_API: '1' } })
const functionsManifestPath = join(
distDir,
'server',
'functions-manifest.json'
)
const content = JSON.parse(fs.readFileSync(functionsManifestPath, 'utf8'))
const { pages } = content
const pageNames = Object.keys(pages)
const paths = [
'/',
'/next-api/link',
'/routes/[dynamic]',
// @TODO: Implement per-page runtime in functions-manifest.
// '/runtime'
]
paths.forEach((path) => {
const { runtime, files } = pages[path]
expect(pageNames).toContain(path)
// Runtime of page `/runtime` is configured as `nodejs`.
expect(runtime).toBe(path === '/runtime' ? 'nodejs' : 'web')
expect(files.every((f) => f.startsWith('server/'))).toBe(true)
})
expect(content.version).toBe(1)
})
}
...@@ -22,7 +22,6 @@ import css from './css' ...@@ -22,7 +22,6 @@ import css from './css'
import rsc from './rsc' import rsc from './rsc'
import streaming from './streaming' import streaming from './streaming'
import basic from './basic' import basic from './basic'
import runtime from './runtime'
import { getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage } from 'next/dist/build/utils' import { getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage } from 'next/dist/build/utils'
const appWithGlobalCss = ` const appWithGlobalCss = `
...@@ -59,7 +58,6 @@ const edgeRuntimeBasicSuite = { ...@@ -59,7 +58,6 @@ const edgeRuntimeBasicSuite = {
basic(context, options) basic(context, options)
streaming(context, options) streaming(context, options)
rsc(context, options) rsc(context, options)
runtime(context, options)
if (env === 'dev') { if (env === 'dev') {
it('should have content-type and content-encoding headers', async () => { it('should have content-type and content-encoding headers', async () => {
......
...@@ -7,6 +7,12 @@ import { getNodeBySelector } from './utils' ...@@ -7,6 +7,12 @@ import { getNodeBySelector } from './utils'
export default function (context, { runtime, env }) { export default function (context, { runtime, env }) {
const distDir = join(context.appDir, '.next') const distDir = join(context.appDir, '.next')
it('should support api routes', async () => {
const res = await renderViaHTTP(context.appPort, '/api/ping')
expect(res).toContain('pong')
})
it('should render server components correctly', async () => { it('should render server components correctly', async () => {
const homeHTML = await renderViaHTTP(context.appPort, '/', null, { const homeHTML = await renderViaHTTP(context.appPort, '/', null, {
headers: { headers: {
...@@ -22,6 +28,7 @@ export default function (context, { runtime, env }) { ...@@ -22,6 +28,7 @@ export default function (context, { runtime, env }) {
expect(homeHTML).toContain('component:index.server') expect(homeHTML).toContain('component:index.server')
expect(homeHTML).toContain('env:env_var_test') expect(homeHTML).toContain('env:env_var_test')
expect(homeHTML).toContain('header:test-util') expect(homeHTML).toContain('header:test-util')
expect(homeHTML).toMatch(/<\/body><\/html>$/)
expect(scriptTagContent).toBe(';') expect(scriptTagContent).toBe(';')
}) })
......
import { renderViaHTTP } from 'next-test-utils'
import { join } from 'path'
import fs from 'fs-extra'
export default async function runtime(context, { runtime, env }) {
const distDir = join(context.appDir, '.next')
if (runtime === 'edge') {
it('should support per-page runtime configuration', async () => {
const html1 = await renderViaHTTP(context.appPort, '/runtime')
expect(html1).toContain('Runtime: Node.js')
const html2 = await renderViaHTTP(context.appPort, '/runtime-rsc')
expect(html2).toContain('Runtime: Node.js')
})
}
if (runtime === 'edge' && env === 'prod') {
it('should include entrypoints from both runtimes in pages manifest', async () => {
const distServerDir = join(distDir, 'server')
const pagesManifest = await fs.readJSON(
join(distServerDir, 'pages-manifest.json')
)
for (const key of [
// Defaults:
'/_app',
'/_error',
'/_document',
// Special:
'/404',
// API routes:
'/api/ping',
// Edge runtime pages:
'/streaming',
'/streaming-rsc',
// Node runtime pages:
'/runtime',
'/runtime-rsc',
]) {
expect(key in pagesManifest).toBeTruthy()
}
})
}
}
/* eslint-env jest */ /* eslint-env jest */
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { fetchViaHTTP, waitFor } from 'next-test-utils' import { fetchViaHTTP } from 'next-test-utils'
import { getNodeBySelector } from './utils' import { getNodeBySelector } from './utils'
async function resolveStreamResponse(response, onData) { async function resolveStreamResponse(response, onData) {
...@@ -94,103 +94,6 @@ export default function (context, { env, runtime }) { ...@@ -94,103 +94,6 @@ export default function (context, { env, runtime }) {
) )
}) })
it('should flush the suffix at the very end', async () => {
await fetchViaHTTP(context.appPort, '/').then(async (response) => {
const result = await resolveStreamResponse(response)
expect(result).toMatch(/<\/body><\/html>/)
})
})
if (env === 'dev') {
it('should warn when stylesheets or scripts are in head', async () => {
let browser
try {
browser = await webdriver(context.appPort, '/head')
await browser.waitForElementByCss('h1')
await waitFor(1000)
const browserLogs = await browser.log('browser')
let foundStyles = false
let foundScripts = false
const logs = []
browserLogs.forEach(({ message }) => {
if (message.includes('Do not add stylesheets using next/head')) {
foundStyles = true
logs.push(message)
}
if (message.includes('Do not add <script> tags using next/head')) {
foundScripts = true
logs.push(message)
}
})
expect(foundStyles).toEqual(true)
expect(foundScripts).toEqual(true)
// Warnings are unique
expect(logs.length).toEqual(new Set(logs).size)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should warn when scripts are in head', async () => {
let browser
try {
browser = await webdriver(context.appPort, '/head')
await browser.waitForElementByCss('h1')
await waitFor(1000)
const browserLogs = await browser.log('browser')
let found = false
browserLogs.forEach((log) => {
if (log.message.includes('Use next/script instead')) {
found = true
}
})
expect(found).toEqual(true)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should not warn when application/ld+json scripts are in head', async () => {
let browser
try {
browser = await webdriver(context.appPort, '/head-with-json-ld-snippet')
await browser.waitForElementByCss('h1')
await waitFor(1000)
const browserLogs = await browser.log('browser')
let found = false
browserLogs.forEach((log) => {
if (log.message.includes('Use next/script instead')) {
found = true
}
})
expect(found).toEqual(false)
} finally {
if (browser) {
await browser.close()
}
}
})
}
it('should stream to users', async () => {
const res = await fetchViaHTTP(context.appPort, '/streaming')
let flushCount = 0
await resolveStreamResponse(res, () => {
flushCount++
})
expect(flushCount).toBeGreaterThan(1)
if (runtime === 'nodejs') {
expect(res.headers.get('etag')).toBeNull()
}
})
it('should not stream to crawlers or google pagerender bot', async () => { it('should not stream to crawlers or google pagerender bot', async () => {
const res1 = await fetchViaHTTP( const res1 = await fetchViaHTTP(
context.appPort, context.appPort,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment