Unverified Commit 75256334 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

DX: display highlited pesudo html when bad nesting html error occurred (#62590)

### What

When you have bad nesting html in your React code, React wil raise
hydration error since the browser html parser might parse it to sth else
different comparing to server html on client. Previously we're display
only the warning in the error description in dev overlay.

Now we introduced another format of displaying pesudo html that
representing your code, with highlighting the html tag that causes the
error. Since React might gives you the whole component stack of React
tree, so we also introduced a way that can collapse the error.

#### Example


https://github.com/vercel/next.js/assets/4800338/622122d6-4d2e-4c8e-95e8-4864343e478b

### Why
The reason we added this is that even we show the html diff, it could
super large due to React ordering the html on client, so the mismatch
might be a lot. The idea here is similar to what you saw when you passed
down a bad event handler into server component, we displayed a pesudo
html as it could hit your mind faster than just seeing the warning. The
best way is to display the source code, but before we can show the
source, getting component stack display as pseudo html instead of here
could be more helpful.



### After vs Before

<img width="400"
src="https://github.com/vercel/next.js/assets/4800338/714119ad-ff23-46a9-bc5a-5601eb390e71">
<img width="400"
src="https://github.com/vercel/next.js/assets/4800338/575f95fa-889e-4cee-ad19-9c2fea06519a">



Closes NEXT-2621
parent 340125a7
......@@ -38,6 +38,7 @@ export interface UnhandledErrorAction {
reason: Error
frames: StackFrame[]
componentStackFrames?: ComponentStackFrame[]
warning?: [string, string, string]
}
export interface UnhandledRejectionAction {
type: typeof ACTION_UNHANDLED_REJECTION
......
......@@ -41,6 +41,7 @@ import type {
} from '../../../../server/dev/hot-reloader-types'
import { extractModulesFromTurbopackMessage } from '../../../../server/dev/extract-modules-from-turbopack-message'
import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../../../dev/error-overlay/messages'
import type { HydrationErrorState } from '../internal/helpers/hydration-error-info'
interface Dispatcher {
onBuildOk(): void
......@@ -496,14 +497,20 @@ export default function HotReload({
}, [dispatch])
const handleOnUnhandledError = useCallback((error: Error): void => {
const errorDetails = (error as any).details as
| HydrationErrorState
| undefined
// Component stack is added to the error in use-error-handler in case there was a hydration errror
const componentStack = (error as any)._componentStack
const componentStack = errorDetails?.componentStack
const warning = errorDetails?.warning
dispatch({
type: ACTION_UNHANDLED_ERROR,
reason: error,
frames: parseStack(error.stack!),
componentStackFrames:
componentStack && parseComponentStack(componentStack),
componentStackFrames: componentStack
? parseComponentStack(componentStack)
: undefined,
warning,
})
}, [])
const handleOnUnhandledRejection = useCallback((reason: Error): void => {
......
......@@ -25,6 +25,11 @@ import { VersionStalenessInfo } from '../components/VersionStalenessInfo'
import type { VersionInfo } from '../../../../../server/dev/parse-version-info'
import { getErrorSource } from '../../../../../shared/lib/error-source'
import { HotlinkedText } from '../components/hot-linked-text'
import { PseudoHtml } from './RuntimeError/component-stack-pseudo-html'
import {
isHtmlTagsWarning,
type HydrationErrorState,
} from '../helpers/hydration-error-info'
export type SupportedErrorEvent = {
id: number
......@@ -214,10 +219,24 @@ export function Errors({
)
}
const error = activeError.error
const isServerError = ['server', 'edge-server'].includes(
getErrorSource(activeError.error) || ''
getErrorSource(error) || ''
)
const errorDetails: HydrationErrorState = (error as any).details || {}
const [warningTemplate, serverContent, clientContent] =
errorDetails.warning || [null, '', '']
const isHtmlTagsWarningTemplate = isHtmlTagsWarning(warningTemplate)
const hydrationWarning = warningTemplate
? warningTemplate
.replace('%s', serverContent)
.replace('%s', clientContent)
.replace('%s', '') // remove the last %s for stack
.replace(/^Warning: /, '')
: null
return (
<Overlay>
<Dialog
......@@ -246,10 +265,23 @@ export function Errors({
<h1 id="nextjs__container_errors_label">
{isServerError ? 'Server Error' : 'Unhandled Runtime Error'}
</h1>
<p id="nextjs__container_errors_desc">
{activeError.error.name}:{' '}
<HotlinkedText text={activeError.error.message} />
<p
id="nextjs__container_errors_desc"
className="nextjs__container_errors_desc nextjs__container_errors_desc--error"
>
{error.name}: <HotlinkedText text={error.message} />
</p>
{hydrationWarning && activeError.componentStackFrames && (
<>
<p id="nextjs__container_errors__extra">{hydrationWarning}</p>
<PseudoHtml
className="nextjs__container_errors__extra_code"
componentStackFrames={activeError.componentStackFrames}
serverTagName={isHtmlTagsWarningTemplate ? serverContent : ''}
clientTagName={isHtmlTagsWarningTemplate ? clientContent : ''}
/>
</>
)}
{isServerError ? (
<div>
<small>
......@@ -284,16 +316,24 @@ export const styles = css`
.nextjs-container-errors-header small > span {
font-family: var(--font-stack-monospace);
}
.nextjs-container-errors-header > p {
.nextjs-container-errors-header p {
font-family: var(--font-stack-monospace);
font-size: var(--size-font-small);
line-height: var(--size-font-big);
font-weight: bold;
margin: 0;
margin-top: var(--size-gap-half);
color: var(--color-ansi-red);
white-space: pre-wrap;
}
.nextjs__container_errors_desc--error {
color: var(--color-ansi-red);
}
.nextjs__container_errors__extra {
margin: 20px 0;
}
nextjs__container_errors__extra__code {
margin: 10px 0;
}
.nextjs-container-errors-header > div > small {
margin: 0;
margin-top: var(--size-gap-half);
......@@ -309,7 +349,9 @@ export const styles = css`
margin-bottom: var(--size-gap);
font-size: var(--size-font-big);
}
.nextjs__container_errors__extra_code {
margin: 20px 0;
}
.nextjs-toast-errors-parent {
cursor: pointer;
transition: transform 0.2s ease;
......
......@@ -2,6 +2,31 @@ import type { StackFramesGroup } from '../../helpers/group-stack-frames-by-frame
import { CallStackFrame } from './CallStackFrame'
import { FrameworkIcon } from './FrameworkIcon'
export function CollapseIcon(
{ collapsed }: { collapsed?: boolean } = { collapsed: false }
) {
// If is not collapsed, rotate 90 degrees
return (
<svg
data-nextjs-call-stack-chevron-icon
data-collapsed={collapsed}
fill="none"
height="20"
width="20"
shapeRendering="geometricPrecision"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
viewBox="0 0 24 24"
// rotate 90 degrees if not collapsed
style={{ transform: collapsed ? undefined : 'rotate(90deg)' }}
>
<path d="M9 18l6-6-6-6" />
</svg>
)
}
function FrameworkGroup({
framework,
stackFrames,
......@@ -13,20 +38,7 @@ function FrameworkGroup({
<details data-nextjs-collapsed-call-stack-details>
{/* Match CallStackFrame tabIndex */}
<summary tabIndex={10}>
<svg
data-nextjs-call-stack-chevron-icon
fill="none"
height="20"
width="20"
shapeRendering="geometricPrecision"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
viewBox="0 0 24 24"
>
<path d="M9 18l6-6-6-6" />
</svg>
<CollapseIcon />
<FrameworkIcon framework={framework} />
{framework === 'react' ? 'React' : 'Next.js'}
</summary>
......
import { useMemo, Fragment, useState } from 'react'
import type { ComponentStackFrame } from '../../helpers/parse-component-stack'
import { CollapseIcon } from './GroupedStackFrames'
const MAX_NON_COLLAPSED_FRAMES = 6
/**
*
* Format component stack into pseudo HTML
* component stack is an array of strings, e.g.: ['p', 'p', 'Page', ...]
*
* Will render it for the code block
*
* <pre>
* <code>{`
* <Page>
* <p>
* ^^^^
* <p>
* ^^^^
* `}</code>
* </pre>
*
*/
export function PseudoHtml({
componentStackFrames,
serverTagName,
clientTagName,
...props
}: {
componentStackFrames: ComponentStackFrame[]
serverTagName?: string
clientTagName?: string
[prop: string]: any
}) {
const isHtmlTagsWarning = serverTagName || clientTagName
const shouldCollapse = componentStackFrames.length > MAX_NON_COLLAPSED_FRAMES
const [isHtmlCollapsed, toggleCollapseHtml] = useState(shouldCollapse)
const htmlComponents = useMemo(() => {
const tagNames = [serverTagName, clientTagName]
const nestedHtmlStack: React.ReactNode[] = []
let lastText = ''
componentStackFrames
.map((frame) => frame.component)
.reverse()
.forEach((component, index, componentList) => {
const spaces = ' '.repeat(nestedHtmlStack.length * 2)
const prevComponent = componentList[index - 1]
const nextComponent = componentList[index + 1]
// When component is the server or client tag name, highlight it
const isHighlightedTag = tagNames.includes(component)
const isRelatedTag =
isHighlightedTag ||
tagNames.includes(prevComponent) ||
tagNames.includes(nextComponent)
if (
nestedHtmlStack.length >= MAX_NON_COLLAPSED_FRAMES &&
isHtmlCollapsed
) {
return
}
if (isRelatedTag) {
const TextWrap = isHighlightedTag ? 'b' : Fragment
const codeLine = (
<span>
<span>{spaces}</span>
<TextWrap>
{'<'}
{component}
{'>'}
{'\n'}
</TextWrap>
</span>
)
lastText = component
const wrappedCodeLine = (
<Fragment key={nestedHtmlStack.length}>
{codeLine}
{/* Add ^^^^ to the target tags */}
{isHighlightedTag && (
<span>{spaces + '^'.repeat(component.length + 2) + '\n'}</span>
)}
</Fragment>
)
nestedHtmlStack.push(wrappedCodeLine)
} else {
if (!isHtmlCollapsed || !isHtmlTagsWarning) {
nestedHtmlStack.push(
<span key={nestedHtmlStack.length}>
{spaces}
{'<' + component + '>\n'}
</span>
)
} else if (lastText !== '...') {
lastText = '...'
nestedHtmlStack.push(
<span key={nestedHtmlStack.length}>
{spaces}
{'...'}
{'\n'}
</span>
)
}
}
})
return nestedHtmlStack
}, [
componentStackFrames,
isHtmlCollapsed,
clientTagName,
serverTagName,
isHtmlTagsWarning,
])
return (
<div data-nextjs-container-errors-pseudo-html>
<span
data-nextjs-container-errors-pseudo-html-collapse
onClick={() => toggleCollapseHtml(!isHtmlCollapsed)}
>
<CollapseIcon collapsed={isHtmlCollapsed} />
</span>
<pre {...props}>
<code>{htmlComponents}</code>
</pre>
</div>
)
}
......@@ -4,7 +4,6 @@ import type { ReadyRuntimeError } from '../../helpers/getErrorByType'
import { noop as css } from '../../helpers/noop-template'
import { groupStackFramesByFramework } from '../../helpers/group-stack-frames-by-framework'
import { GroupedStackFrames } from './GroupedStackFrames'
import { ComponentStackFrameRow } from './ComponentStackFrameRow'
export type RuntimeErrorProps = { error: ReadyRuntimeError }
......@@ -77,18 +76,6 @@ export function RuntimeError({ error }: RuntimeErrorProps) {
</React.Fragment>
) : undefined}
{error.componentStackFrames ? (
<>
<h2>Component Stack</h2>
{error.componentStackFrames.map((componentStackFrame, index) => (
<ComponentStackFrameRow
key={index}
componentStackFrame={componentStackFrame}
/>
))}
</>
) : null}
{stackFramesGroupedByFramework.length ? (
<React.Fragment>
<h2>Call Stack</h2>
......@@ -200,4 +187,14 @@ export const styles = css`
[data-nextjs-collapsed-call-stack-details] [data-nextjs-call-stack-frame] {
margin-bottom: var(--size-gap-double);
}
[data-nextjs-container-errors-pseudo-html] {
position: relative;
padding-left: var(--size-gap-triple);
}
[data-nextjs-container-errors-pseudo-html-collapse] {
position: absolute;
left: 0;
}
`
export let hydrationErrorWarning: string | undefined
export let hydrationErrorComponentStack: string | undefined
export type HydrationErrorState = {
// [message, serverContent, clientContent]
warning?: [string, string, string]
componentStack?: string
serverContent?: string
clientContent?: string
}
export const hydrationErrorState: HydrationErrorState = {}
const htmlTagsWarnings = new Set([
'Warning: In HTML, %s cannot be a descendant of <%s>.\nThis will cause a hydration error.%s',
'Warning: Expected server HTML to contain a matching <%s> in <%s>.%s',
'Warning: Did not expect server HTML to contain a <%s> in <%s>.%s',
])
// https://github.com/facebook/react/blob/main/packages/react-dom/src/__tests__/ReactDOMHydrationDiff-test.js used as a reference
const knownHydrationWarnings = new Set([
'Warning: In HTML, %s cannot be a descendant of <%s>.\nThis will cause a hydration error.%s',
...htmlTagsWarnings,
'Warning: Text content did not match. Server: "%s" Client: "%s"%s',
'Warning: Expected server HTML to contain a matching <%s> in <%s>.%s',
'Warning: Expected server HTML to contain a matching text node for "%s" in <%s>.%s',
'Warning: Did not expect server HTML to contain a <%s> in <%s>.%s',
'Warning: Did not expect server HTML to contain the text node "%s" in <%s>.%s',
])
......@@ -21,14 +31,21 @@ export function patchConsoleError() {
const prev = console.error
console.error = function (msg, serverContent, clientContent, componentStack) {
if (knownHydrationWarnings.has(msg)) {
hydrationErrorWarning = msg
.replace('%s', serverContent)
.replace('%s', clientContent)
.replace('%s', '')
hydrationErrorComponentStack = componentStack
hydrationErrorState.warning = [
// remove the last %s from the message
msg,
serverContent,
clientContent,
]
hydrationErrorState.componentStack = componentStack
hydrationErrorState.serverContent = serverContent
hydrationErrorState.clientContent = clientContent
}
// @ts-expect-error argument is defined
prev.apply(console, arguments)
}
}
export const isHtmlTagsWarning = (msg: any) =>
Boolean(msg && htmlTagsWarnings.has(msg))
import { useEffect } from 'react'
import {
hydrationErrorWarning,
hydrationErrorComponentStack,
} from './hydration-error-info'
import { hydrationErrorState } from './hydration-error-info'
import { isNextRouterError } from '../../../is-next-router-error'
import { isHydrationError } from '../../../is-hydration-error'
......@@ -48,17 +45,19 @@ if (typeof window !== 'undefined') {
'https://nextjs.org/docs/messages/react-hydration-error'
)
) {
if (hydrationErrorWarning) {
// If there's any extra information in the error message to display,
// append it to the error message details property
if (hydrationErrorState.warning) {
// The patched console.error found hydration errors logged by React
// Append the logged warning to the error message
error.message += '\n\n' + hydrationErrorWarning
}
if (hydrationErrorComponentStack) {
// Hydration error component stack is added to the error, it's picked up by the hot-reloader-client
;(error as any)._componentStack = hydrationErrorComponentStack
;(error as any).details = {
...(error as any).details,
// It contains the warning, component stack, server and client tag names
...hydrationErrorState,
}
}
error.message +=
'\n\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error'
'\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error'
}
const e = error
......
......@@ -2,8 +2,7 @@ import * as Bus from './bus'
import { parseStack } from '../internal/helpers/parseStack'
import { parseComponentStack } from '../internal/helpers/parse-component-stack'
import {
hydrationErrorComponentStack,
hydrationErrorWarning,
hydrationErrorState,
patchConsoleError,
} from '../internal/helpers/hydration-error-info'
......@@ -23,18 +22,23 @@ function onUnhandledError(ev: ErrorEvent) {
if (
error.message.match(/(hydration|content does not match|did not match)/i)
) {
if (hydrationErrorWarning) {
if (hydrationErrorState.warning) {
// The patched console.error found hydration errors logged by React
// Append the logged warning to the error message
error.message += '\n\n' + hydrationErrorWarning
;(error as any).details = {
...(error as any).details,
// It contains the warning, component stack, server and client tag names
...hydrationErrorState,
}
}
error.message += `\n\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error`
error.message += `\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error`
}
const e = error
const componentStackFrames =
typeof hydrationErrorComponentStack === 'string'
? parseComponentStack(hydrationErrorComponentStack)
typeof hydrationErrorState.componentStack === 'string'
? parseComponentStack(hydrationErrorState.componentStack)
: undefined
// Skip ModuleBuildError and ModuleNotFoundError, as it will be sent through onBuildError callback.
......
......@@ -15,7 +15,7 @@ if (!window._nextSetupHydrationWarning) {
if (isHydrateError) {
args = [
...args,
`\n\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error`,
`\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error`,
]
}
origConsoleError.apply(window.console, args)
......
......@@ -18,48 +18,59 @@ describe('Component Stack in error overlay', () => {
await session.waitForAndOpenRuntimeError()
// If it's too long we can collapse
if (process.env.TURBOPACK) {
expect(await session.getRedboxComponentStack()).toMatchInlineSnapshot(`
"p
div
Component
main
Mismatch
InnerLayoutRouter
RedirectErrorBoundary
RedirectBoundary
NotFoundErrorBoundary
NotFoundBoundary
LoadingBoundary
ErrorBoundary
InnerScrollAndFocusHandler
ScrollAndFocusHandler
RenderFromTemplateContext
OuterLayoutRouter
body
html
RootLayout
RedirectErrorBoundary
RedirectBoundary
NotFoundErrorBoundary
NotFoundBoundary
DevRootNotFoundBoundary
ReactDevOverlay
HotReload
Router
ErrorBoundaryHandler
ErrorBoundary
AppRouter
ServerRoot
Root"
"<Root>
<ServerRoot>
<AppRouter>
<ErrorBoundary>
<ErrorBoundaryHandler>
<Router>"
`)
await session.toggleComponentStack()
expect(await session.getRedboxComponentStack()).toMatchInlineSnapshot(`
"<Root>
<ServerRoot>
<AppRouter>
<ErrorBoundary>
<ErrorBoundaryHandler>
<Router>
<HotReload>
<ReactDevOverlay>
<DevRootNotFoundBoundary>
<NotFoundBoundary>
<NotFoundErrorBoundary>
<RedirectBoundary>
<RedirectErrorBoundary>
<RootLayout>
<html>
<body>
<OuterLayoutRouter>
<RenderFromTemplateContext>
<ScrollAndFocusHandler>
<InnerScrollAndFocusHandler>
<ErrorBoundary>
<LoadingBoundary>
<NotFoundBoundary>
<NotFoundErrorBoundary>
<RedirectBoundary>
<RedirectErrorBoundary>
<InnerLayoutRouter>
<Mismatch>
<main>
<Component>
<div>
<p>"
`)
} else {
expect(await session.getRedboxComponentStack()).toMatchInlineSnapshot(`
"p
div
Component
main
Mismatch"
"<Mismatch>
<main>
<Component>
<div>
<p>"
`)
}
......
......@@ -7,7 +7,7 @@ import { outdent } from 'outdent'
// https://github.com/facebook/react/blob/main/packages/react-dom/src/__tests__/ReactDOMHydrationDiff-test.js used as a reference
describe('Error overlay for hydration errors', () => {
const { next } = nextTestSetup({
const { next, isTurbopack } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
dependencies: {
react: 'latest',
......@@ -41,12 +41,13 @@ describe('Error overlay for hydration errors', () => {
expect(await session.getRedboxDescription()).toMatchInlineSnapshot(`
"Error: Text content does not match server-rendered HTML.
Warning: Text content did not match. Server: "server" Client: "client"
See more info here: https://nextjs.org/docs/messages/react-hydration-error"
`)
expect(await session.getRedboxDescriptionWarning()).toMatchInlineSnapshot(
`"Text content did not match. Server: "server" Client: "client""`
)
await session.patch(
'app/page.js',
outdent`
......@@ -93,11 +94,11 @@ describe('Error overlay for hydration errors', () => {
expect(await session.getRedboxDescription()).toMatchInlineSnapshot(`
"Error: Hydration failed because the initial UI does not match what was rendered on the server.
Warning: Expected server HTML to contain a matching <main> in <div>.
See more info here: https://nextjs.org/docs/messages/react-hydration-error"
`)
`)
expect(await session.getRedboxDescriptionWarning()).toMatchInlineSnapshot(
`"Expected server HTML to contain a matching <main> in <div>."`
)
await cleanup()
})
......@@ -128,12 +129,13 @@ describe('Error overlay for hydration errors', () => {
expect(await session.getRedboxDescription()).toMatchInlineSnapshot(`
"Error: Hydration failed because the initial UI does not match what was rendered on the server.
Warning: Expected server HTML to contain a matching text node for "second" in <div>.
See more info here: https://nextjs.org/docs/messages/react-hydration-error"
`)
expect(await session.getRedboxDescriptionWarning()).toMatchInlineSnapshot(
`"Expected server HTML to contain a matching text node for "second" in <div>."`
)
await cleanup()
})
......@@ -162,11 +164,11 @@ describe('Error overlay for hydration errors', () => {
expect(await session.getRedboxDescription()).toMatchInlineSnapshot(`
"Error: Hydration failed because the initial UI does not match what was rendered on the server.
Warning: Did not expect server HTML to contain a <main> in <div>.
See more info here: https://nextjs.org/docs/messages/react-hydration-error"
`)
expect(await session.getRedboxDescriptionWarning()).toMatchInlineSnapshot(
`"Did not expect server HTML to contain a <main> in <div>."`
)
await cleanup()
})
......@@ -192,12 +194,13 @@ describe('Error overlay for hydration errors', () => {
expect(await session.getRedboxDescription()).toMatchInlineSnapshot(`
"Error: Hydration failed because the initial UI does not match what was rendered on the server.
Warning: Did not expect server HTML to contain the text node "only" in <div>.
See more info here: https://nextjs.org/docs/messages/react-hydration-error"
`)
expect(await session.getRedboxDescriptionWarning()).toMatchInlineSnapshot(
`"Did not expect server HTML to contain the text node "only" in <div>."`
)
await cleanup()
})
......@@ -231,12 +234,13 @@ describe('Error overlay for hydration errors', () => {
expect(await session.getRedboxDescription()).toMatchInlineSnapshot(`
"Error: Hydration failed because the initial UI does not match what was rendered on the server.
Warning: Expected server HTML to contain a matching <main> in <div>.
See more info here: https://nextjs.org/docs/messages/react-hydration-error"
`)
expect(await session.getRedboxDescriptionWarning()).toMatchInlineSnapshot(
`"Expected server HTML to contain a matching <main> in <div>."`
)
await cleanup()
})
......@@ -311,9 +315,100 @@ describe('Error overlay for hydration errors', () => {
expect(description).toContain(
'Error: Hydration failed because the initial UI does not match what was rendered on the server.'
)
const warning = await session.getRedboxDescriptionWarning()
expect(warning).toContain(
'In HTML, <p> cannot be a descendant of <p>.\nThis will cause a hydration error.'
)
const pseudoHtml = await browser
.elementByCss('[data-nextjs-container-errors-pseudo-html] code')
.text()
// Turbopack currently has longer component stack trace
if (isTurbopack) {
expect(pseudoHtml).toMatchInlineSnapshot(`
"...
<Page>
<p>
^^^
<p>
^^^
"
`)
} else {
expect(pseudoHtml).toMatchInlineSnapshot(`
"<Page>
<p>
^^^
<p>
^^^
"
`)
}
await cleanup()
})
it('should show the highlighted bad nesting html snippet when bad nesting happened', async () => {
const { cleanup, session, browser } = await sandbox(
next,
new Map([
[
'app/page.js',
outdent`
'use client'
export default function Page() {
return (
<p><span><span><span><span><p>hello world</p></span></span></span></span></p>
)
}
`,
],
])
)
await session.waitForAndOpenRuntimeError()
expect(await session.hasRedbox()).toBe(true)
const description = await session.getRedboxDescription()
expect(description).toContain(
'Warning: In HTML, <p> cannot be a descendant of <p>.\nThis will cause a hydration error.'
'Error: Hydration failed because the initial UI does not match what was rendered on the server.'
)
const warning = await session.getRedboxDescriptionWarning()
expect(warning).toContain(
'In HTML, <p> cannot be a descendant of <p>.\nThis will cause a hydration error.'
)
const pseudoHtml = await browser
.elementByCss('[data-nextjs-container-errors-pseudo-html] code')
.text()
// Turbopack currently has longer component stack trace
if (isTurbopack) {
expect(pseudoHtml).toMatchInlineSnapshot(`
"...
<Page>
<p>
^^^
<span>
...
<span>
"
`)
} else {
expect(pseudoHtml).toMatchInlineSnapshot(`
"<Page>
<p>
^^^
<span>
...
<span>
<p>
^^^
"
`)
}
await cleanup()
})
......
......@@ -16,26 +16,20 @@ createNextDescribe(
if (process.env.TURBOPACK) {
expect(await getRedboxComponentStack(browser)).toMatchInlineSnapshot(`
"p
div
Component
main
Mismatch
App
PathnameContextProviderAdapter
ErrorBoundary
ReactDevOverlay
Container
AppContainer
Root"
"<Root>
<AppContainer>
<Container>
<ReactDevOverlay>
<ErrorBoundary>
<PathnameContextProviderAdapter>"
`)
} else {
expect(await getRedboxComponentStack(browser)).toMatchInlineSnapshot(`
"p
div
Component
main
Mismatch"
"<Mismatch>
<main>
<Component>
<div>
<p>"
`)
}
})
......
......@@ -38,12 +38,13 @@ describe('Error overlay for hydration errors', () => {
expect(await session.getRedboxDescription()).toMatchInlineSnapshot(`
"Error: Text content does not match server-rendered HTML.
Warning: Text content did not match. Server: "server" Client: "client"
See more info here: https://nextjs.org/docs/messages/react-hydration-error"
`)
expect(await session.getRedboxDescriptionWarning()).toMatchInlineSnapshot(
`"Text content did not match. Server: "server" Client: "client""`
)
await session.patch(
'index.js',
outdent`
......
......@@ -8,6 +8,8 @@ import {
hasRedbox,
waitFor,
waitForAndOpenRuntimeError,
getRedboxDescriptionWarning,
toggleComponentStack,
} from './next-test-utils'
import webdriver from './next-webdriver'
import { NextInstance } from './next-modes/base'
......@@ -122,6 +124,9 @@ export async function sandbox(
async getRedboxDescription() {
return getRedboxDescription(browser)
},
async getRedboxDescriptionWarning() {
return getRedboxDescriptionWarning(browser)
},
async getRedboxSource(includeHeader = false) {
const header = includeHeader ? await getRedboxHeader(browser) : ''
const source = await getRedboxSource(browser)
......@@ -134,6 +139,9 @@ export async function sandbox(
async getRedboxComponentStack() {
return getRedboxComponentStack(browser)
},
async toggleComponentStack() {
return toggleComponentStack(browser)
},
async getVersionCheckerText() {
return getVersionCheckerText(browser)
},
......
......@@ -834,6 +834,27 @@ export async function getRedboxDescription(browser: BrowserInterface) {
)
}
export async function getRedboxDescriptionWarning(browser: BrowserInterface) {
return retry(
() =>
evaluate(browser, () => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p) =>
p.shadowRoot.querySelector('[data-nextjs-dialog-header]')
)
const root = portal.shadowRoot
const text = root.querySelector(
'#nextjs__container_errors__extra'
)?.innerText
return text
}),
3000,
500,
'getRedboxDescriptionWarning'
)
}
export function getBrowserBodyText(browser: BrowserInterface) {
return browser.eval('document.getElementsByTagName("body")[0].innerText')
}
......@@ -1058,12 +1079,12 @@ export async function getRedboxComponentStack(
browser: BrowserInterface
): Promise<string> {
await browser.waitForElementByCss(
'[data-nextjs-component-stack-frame]',
'[data-nextjs-container-errors-pseudo-html]',
30000
)
// TODO: the type for elementsByCss is incorrect
const componentStackFrameElements: any = await browser.elementsByCss(
'[data-nextjs-component-stack-frame]'
'[data-nextjs-container-errors-pseudo-html]'
)
const componentStackFrameTexts = await Promise.all(
componentStackFrameElements.map((f) => f.innerText())
......@@ -1072,6 +1093,14 @@ export async function getRedboxComponentStack(
return componentStackFrameTexts.join('\n').trim()
}
export async function toggleComponentStack(
browser: BrowserInterface
): Promise<void> {
await browser
.elementByCss('[data-nextjs-container-errors-pseudo-html-collapse]')
.click()
}
export async function expandCallStack(
browser: BrowserInterface
): Promise<void> {
......
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