Unverified Commit 41a2eb23 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Clean up legacy react 18 tests (#35615)

### source changes
* Error dynamic suspense option in non concurrent mode, don't check react root anymore since they should be bound

### tests changes

* Remove duplicated rsc client test
* Merge type checking cases (`next/dynamic`)
* Remove blocking rendering tests cases since we should opt-in Fizz rendering when using React.lazy
* Remove some thrown promises cases, leverage the streaming component we had in RSC test
parent 4bfcf834
......@@ -117,14 +117,11 @@ export default function dynamic<P = {}>(
const suspenseOptions = loadableOptions as LoadableSuspenseOptions & {
loader: Loader<P>
}
if (!process.env.__NEXT_CONCURRENT_FEATURES) {
// Error if react root is not enabled and `suspense` option is set to true
if (!process.env.__NEXT_REACT_ROOT && suspenseOptions.suspense) {
// TODO: add error doc when this feature is stable
throw new Error(
`Invalid suspense option usage in next/dynamic. Read more: https://nextjs.org/docs/messages/invalid-dynamic-suspense`
)
}
// Error if Fizz rendering is not enabled and `suspense` option is set to true
if (!process.env.__NEXT_CONCURRENT_FEATURES && suspenseOptions.suspense) {
throw new Error(
`Invalid suspense option usage in next/dynamic. Read more: https://nextjs.org/docs/messages/invalid-dynamic-suspense`
)
}
if (suspenseOptions.suspense) {
return loadableFn(suspenseOptions)
......
......@@ -6,6 +6,7 @@ import { File, nextBuild } from 'next-test-utils'
const appDir = __dirname
const nextConfig = new File(join(appDir, 'next.config.js'))
const reactDomPackagePah = join(appDir, 'node_modules/react-dom')
function writeNextConfig(config) {
const content = `module.exports = { experimental: ${JSON.stringify(config)} }`
......@@ -24,21 +25,36 @@ describe('Invalid react 18 webpack config', () => {
'`experimental.runtime` requires `experimental.reactRoot` to be enabled along with React 18.'
)
})
})
it('should warn user when not using react 18 and `experimental.reactRoot` is enabled', async () => {
const reactDomPackagePah = join(appDir, 'node_modules/react-dom')
describe('React 17 with React 18 config', () => {
beforeAll(async () => {
await fs.mkdirp(reactDomPackagePah)
await fs.writeFile(
join(reactDomPackagePah, 'package.json'),
JSON.stringify({ name: 'react-dom', version: '17.0.0' })
)
writeNextConfig({ reactRoot: true })
const { stderr } = await nextBuild(appDir, [], { stderr: true })
})
afterAll(async () => {
await fs.remove(reactDomPackagePah)
nextConfig.restore()
})
it('should warn user when not using react 18 and `experimental.reactRoot` is enabled', async () => {
const { stderr } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).toContain(
'You have to use React 18 to use `experimental.reactRoot`.'
)
})
it('suspense is not allowed in blocking rendering mode', async () => {
const { stderr, code } = await nextBuild(appDir, [], {
stderr: true,
})
expect(stderr).toContain(
'Invalid suspense option usage in next/dynamic. Read more: https://nextjs.org/docs/messages/invalid-dynamic-suspense'
)
expect(code).toBe(1)
})
})
import React, { Suspense } from 'react'
import dynamic from 'next/dynamic'
const DynamicFoo = dynamic(() => import('../../components/ts-foo'), {
suspense: true,
})
const Foo = dynamic(() => import('../components/foo'), { suspense: true })
export default function Typing() {
export default function Dynamic() {
return (
<Suspense fallback={null}>
<DynamicFoo />
<Suspense>
<Foo />
</Suspense>
)
}
import { Suspense } from 'react'
import dynamic from 'next/dynamic'
import { useCachedPromise } from './promise-cache'
const Foo = dynamic(() => import('./foo'), {
suspense: true,
})
export default function Bar() {
useCachedPromise(
'bar',
() => new Promise((resolve) => setTimeout(resolve, 300)),
true
)
return (
<div>
bar
<Suspense fallback={'oof'}>
<Foo />
</Suspense>
</div>
)
}
import { Suspense } from 'react'
import dynamic from 'next/dynamic'
let ssr
const suspense = false
const Hello = dynamic(() => import('./hello'), {
ssr,
suspense,
})
export default function DynamicHello(props) {
return (
<Suspense fallback={'loading'}>
<Hello {...props} />
</Suspense>
)
}
export default function Foo() {
return 'foo'
}
import React from 'react'
import ReactDOM from 'react-dom'
import { useCachedPromise } from './promise-cache'
export default function Hello({ name, thrown = false }) {
useCachedPromise(
name,
() => new Promise((resolve) => setTimeout(resolve, 200)),
thrown
)
const [hydrated, setHydrated] = React.useState(() => false)
React.useEffect(() => {
if (!hydrated) {
setHydrated(true)
}
}, [hydrated])
const serverRendered = React.useMemo(() => {
if (typeof window === 'undefined') {
return true
}
const elem = document.getElementById('server-rendered')
if (elem) {
return elem.innerText === 'true'
}
return false
}, [])
return (
<p>
hello {ReactDOM.version}
<span id="server-rendered">{serverRendered.toString()}</span>
{hydrated ? <span id="hydrated">{hydrated.toString()}</span> : null}
</p>
)
}
import React from 'react'
const PromiseCacheContext = React.createContext(null)
export const cache = new Map()
export const PromiseCacheProvider = PromiseCacheContext.Provider
export function useCachedPromise(key, fn, thrown = false) {
const cache = React.useContext(PromiseCacheContext)
if (!thrown) return undefined
let entry = cache.get(key)
if (!entry) {
entry = {
status: 'PENDING',
value: fn().then(
(value) => {
cache.set(key, {
status: 'RESOLVED',
value,
})
},
(err) => {
cache.set(key, {
status: 'REJECTED',
value: err,
})
}
),
}
cache.set(key, entry)
}
if (['PENDING', 'REJECTED'].includes(entry.status)) {
throw entry.value
}
return entry.value
}
import React from 'react'
import { useCachedPromise } from './promise-cache'
export default function Styled({ name }) {
useCachedPromise(
name,
() => new Promise((resolve) => setTimeout(resolve, 1000)),
true
)
return (
<div>
<p>This is Red.</p>
<style jsx>{`
p {
color: red;
}
`}</style>
</div>
)
}
import React, { Suspense } from 'react'
import { createStreamingData } from '../../test/streaming-data'
const Data = createStreamingData()
export default function Styled() {
return (
<Suspense fallback={`fallback`}>
<Data>
<div>
<p>This is Red.</p>
<style jsx>{`
p {
color: red;
}
`}</style>
</div>
</Data>
</Suspense>
)
}
export default function TsFoo() {
return <div>ts-foo</div>
}
import { PromiseCacheProvider } from '../components/promise-cache'
function MyApp({ Component, pageProps }) {
return (
<PromiseCacheProvider value={new Map()}>
<Component {...pageProps} />
</PromiseCacheProvider>
)
}
export default MyApp
export default function SSR() {
return 'hello'
}
export function getServerSideProps() {
// Prevent static optimization
return { props: {} }
}
import React from 'react'
import { useCachedPromise } from '../../components/promise-cache'
export default function Backpressure() {
const elements = []
for (let i = 0; i < 2000; i++) {
elements.push(
<React.Suspense key={i} fallback={<span>loading...</span>}>
<Item idx={i} />
</React.Suspense>
)
}
return <React.Suspense>{elements}</React.Suspense>
}
function Item({ idx }) {
const key = idx.toString()
if (typeof window === 'undefined') {
// eslint-disable-next-line react-hooks/rules-of-hooks
useCachedPromise(key, () => Promise.resolve(), true)
}
return <span className="item">{key}</span>
}
// Disable offline build
export function getServerSideProps() {
return { props: {} }
}
import { Suspense } from 'react'
import dynamic from 'next/dynamic'
const Bar = dynamic(() => import('../../components/bar'), {
ssr: false,
suspense: true,
// Explicitly declare loaded modules.
// For suspense cases, they'll be ignored.
// For loadable component cases, they'll be handled
loadableGenerated: {
modules: ['../../components/bar'],
webpack: [require.resolveWeak('../../components/bar')],
},
})
export default function NoPreload() {
return (
<Suspense fallback={'fallback'}>
<Bar />
</Suspense>
)
}
import DynamicHello from '../../components/dynamic-hello'
export default function NoThrown() {
return <DynamicHello name="no-thrown" thrown={false} />
}
import DynamicHello from '../../components/dynamic-hello'
export default function Thrown() {
return <DynamicHello name="thrown" thrown />
}
// use tsx to cover typescript usage of next/dynamic + suspense: true
import React from 'react'
import dynamic from 'next/dynamic'
......
......@@ -2,7 +2,7 @@
import webdriver from 'next-webdriver'
import cheerio from 'cheerio'
import { fetchViaHTTP, renderViaHTTP } from 'next-test-utils'
import { renderViaHTTP } from 'next-test-utils'
export default (context) => {
it('no warnings for image related link props', async () => {
......@@ -17,24 +17,6 @@ export default (context) => {
expect(await browser.elementById('react-dom-version').text()).toMatch(/18/)
})
it('should works with suspense in ssg', async () => {
const res1 = await fetchViaHTTP(context.appPort, '/suspense/thrown')
const res2 = await fetchViaHTTP(context.appPort, '/suspense/no-thrown')
expect(res1.status).toBe(200)
expect(res2.status).toBe(200)
})
it('should render fallback without preloads on server side', async () => {
const html = await renderViaHTTP(context.appPort, '/suspense/no-preload')
const $ = cheerio.load(html)
const nextData = JSON.parse($('#__NEXT_DATA__').text())
const content = $('#__next').text()
// <Bar> is suspended
expect(content).toBe('fallback')
expect(nextData.dynamicIds).toBeUndefined()
})
it('useId() values should match on hydration', async () => {
const html = await renderViaHTTP(context.appPort, '/use-id')
const $ = cheerio.load(html)
......
/* eslint-env jest */
import cheerio from 'cheerio'
export default (context, render) => {
async function get$(path, query) {
const html = await render(path, query)
return cheerio.load(html)
}
it('should render fallback on server side if suspense without ssr', async () => {
const $ = await get$('/suspense/no-preload')
const nextData = JSON.parse($('#__NEXT_DATA__').text())
const content = $('#__next').text()
expect(content).toBe('fallback')
expect(nextData.dynamicIds).toBeUndefined()
})
// Testing the same thing as above.
it.skip('should render import fallback on server side if suspended without ssr', async () => {
const $ = await get$('/suspense/thrown')
const html = $('body').html()
expect(html).toContain('loading')
expect(JSON.parse($('#__NEXT_DATA__').text()).dynamicIds).toBeUndefined()
})
}
......@@ -7,7 +7,7 @@ export default (context, _render) => {
async function withBrowser(path, cb) {
let browser
try {
browser = await webdriver(context.appPort, path, false)
browser = await webdriver(context.appPort, path)
await cb(browser)
} finally {
if (browser) {
......@@ -16,61 +16,6 @@ export default (context, _render) => {
}
}
it('should resolve suspense modules on server side if suspense', async () => {
await withBrowser('/suspense/no-preload', async (browser) => {
await check(() => browser.waitForElementByCss('#__next').text(), /barfoo/)
await check(
() => browser.eval('typeof __NEXT_DATA__.dynamicIds'),
/undefined/
)
})
})
it('should resolve suspense on server side if not suspended on server', async () => {
await withBrowser('/suspense/no-thrown', async (browser) => {
await check(
() => browser.waitForElementByCss('#server-rendered').text(),
/true/
)
await check(
() => browser.eval('typeof __NEXT_DATA__.dynamicIds'),
/undefined/
)
})
})
it('should resolve suspense on server side if suspended on server', async () => {
await withBrowser('/suspense/thrown', async (browser) => {
await check(
() => browser.waitForElementByCss('#server-rendered').text(),
/true/
)
await check(
() => browser.eval('typeof __NEXT_DATA__.dynamicIds'),
/undefined/
)
})
})
it('should hydrate suspenses on client side if suspended on server', async () => {
await withBrowser('/suspense/thrown', async (browser) => {
await check(() => browser.waitForElementByCss('#hydrated').text(), /true/)
await check(
() => browser.eval('typeof __NEXT_DATA__.dynamicIds'),
/undefined/
)
})
})
it('should drain the entire response', async () => {
await withBrowser('/suspense/backpressure', async (browser) => {
await check(
() => browser.eval('document.querySelectorAll(".item").length'),
/2000/
)
})
})
it('throws if useFlushEffects is used more than once', async () => {
await renderViaHTTP(context.appPort, '/use-flush-effect/multiple-calls')
expect(context.stderr).toContain(
......@@ -94,7 +39,7 @@ export default (context, _render) => {
/blue/
)
await check(
() => browser.waitForElementByCss('#__jsx-c74678abd3b78a').text(),
() => browser.waitForElementByCss('#__jsx-8b0811664c4e575e').text(),
/red/
)
})
......
......@@ -13,7 +13,6 @@ import {
hasRedbox,
getRedboxHeader,
} from 'next-test-utils'
import blocking from './blocking'
import concurrent from './concurrent'
import basics from './basics'
import strictMode from './strict-mode'
......@@ -23,74 +22,8 @@ import webdriver from 'next-webdriver'
const nodeArgs = ['-r', join(__dirname, 'require-hook.js')]
const appDir = join(__dirname, '../app')
const nextConfig = new File(join(appDir, 'next.config.js'))
const dynamicHello = new File(join(appDir, 'components/dynamic-hello.js'))
const invalidPage = new File(join(appDir, 'pages/invalid.js'))
const USING_CREATE_ROOT = 'Using the createRoot API for React'
async function getBuildOutput(dir) {
const { stdout, stderr } = await nextBuild(dir, [], {
stdout: true,
stderr: true,
nodeArgs,
})
return stdout + stderr
}
async function getDevOutput(dir) {
const port = await findPort()
let stdout = ''
let stderr = ''
let instance = await launchApp(dir, port, {
stdout: true,
stderr: true,
onStdout(msg) {
stdout += msg
},
onStderr(msg) {
stderr += msg
},
nodeArgs,
})
await killApp(instance)
return stdout + stderr
}
describe('React 18 Support', () => {
describe('Use legacy render', () => {
beforeAll(() => {
nextConfig.replace('reactRoot: true', 'reactRoot: false')
})
afterAll(() => {
nextConfig.restore()
})
test('supported version of react in dev', async () => {
const output = await getDevOutput(appDir)
expect(output).not.toMatch(USING_CREATE_ROOT)
})
test('supported version of react in build', async () => {
const output = await getBuildOutput(appDir)
expect(output).not.toMatch(USING_CREATE_ROOT)
})
test('suspense is not allowed in blocking rendering mode', async () => {
nextConfig.replace('withReact18({', '/*withReact18*/({')
const { stderr, code } = await nextBuild(appDir, [], {
stderr: true,
})
nextConfig.replace('/*withReact18*/({', 'withReact18({')
expect(stderr).toContain(
'Invalid suspense option usage in next/dynamic. Read more: https://nextjs.org/docs/messages/invalid-dynamic-suspense'
)
expect(code).toBe(1)
})
})
})
describe('Basics', () => {
runTests('default setting with react 18', (context) => basics(context))
})
......@@ -115,19 +48,6 @@ describe('Strict mode - dev', () => {
strictMode(context)
})
describe('Blocking mode', () => {
beforeAll(() => {
dynamicHello.replace('suspense = false', `suspense = true`)
})
afterAll(() => {
dynamicHello.restore()
})
runTests('`runtime` is disabled', (context) => {
blocking(context, (p, q) => renderViaHTTP(context.appPort, p, q))
})
})
function runTestsAgainstRuntime(runtime) {
runTests(
`Concurrent mode in the ${runtime} runtime`,
......@@ -151,16 +71,12 @@ function runTestsAgainstRuntime(runtime) {
invalidPage.write(`export const value = 1`)
}
nextConfig.replace("// runtime: 'edge'", `runtime: '${runtime}'`)
dynamicHello.replace('suspense = false', `suspense = true`)
// `noSSR` mode will be ignored by suspense
dynamicHello.replace('let ssr', `let ssr = false`)
},
afterAll: (env) => {
if (env === 'dev') {
invalidPage.delete()
}
nextConfig.restore()
dynamicHello.restore()
},
}
)
......
export function createStreamingData() {
let result
let promise
function Data({ children, duration = 500 }) {
if (result) return result
if (!promise)
promise = new Promise((res) => {
setTimeout(() => {
result = children
res()
}, duration)
})
throw promise
}
return Data
}
import { lazy, Suspense } from 'react'
import dynamic from 'next/dynamic'
const Foo = lazy(() => import('../components/foo.client'))
const Bar = dynamic(() => import('../components/bar.client'), {
suspense: true,
})
export default function Page() {
return (
<div>
<Suspense fallback="loading...">
<Suspense fallback="fallback">
<Foo />
<Bar />
</Suspense>
</div>
)
......
import Foo from '../components/foo.client'
import Nav from '../components/nav.server'
const envVar = process.env.ENV_VAR_TEST
......@@ -11,9 +10,6 @@ export default function Index({ header, router }) {
<div>{'path:' + router.pathname}</div>
<div>{'env:' + envVar}</div>
<div>{'header:' + header}</div>
<div>
<Foo />
</div>
<Nav />
</div>
)
......
......@@ -23,12 +23,12 @@ export default function Page() {
<div>
<ClientNamed />
</div>
<di>
<div>
<CjsShared />
</di>
<di>
</div>
<div>
<CjsClient />
</di>
</div>
</div>
)
}
......@@ -61,6 +61,8 @@ export default async function basic(context, { env }) {
const browser = await webdriver(context.appPort, '/dynamic-imports')
const content = await browser.eval(`window.document.body.innerText`)
expect(content).toMatchInlineSnapshot('"foo.client"')
const dynamicIds = await browser.eval(`__NEXT_DATA__.dynamicIds`)
expect(content).toMatchInlineSnapshot('"foo.clientbar.client"')
expect(dynamicIds).toBe(undefined)
})
}
......@@ -20,7 +20,6 @@ export default function (context, { runtime, env }) {
expect(homeHTML).toContain('env:env_var_test')
expect(homeHTML).toContain('header:test-util')
expect(homeHTML).toContain('path:/')
expect(homeHTML).toContain('foo.client')
})
it('should reuse the inline flight response without sending extra requests', async () => {
......
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