Skip to content

Commit

Permalink
Add test
Browse files Browse the repository at this point in the history
  • Loading branch information
Hannes Bornö committed Mar 1, 2023
1 parent 5b94209 commit 3930e5e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
30 changes: 30 additions & 0 deletions packages/next/src/lib/format-server-error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { formatServerError } from './format-server-error'

describe('formatServerError', () => {
it('should not append message several times', () => {
const err = new Error(
'Class extends value undefined is not a constructor or null'
)

// Before
expect(err.message).toMatchInlineSnapshot(
`"Class extends value undefined is not a constructor or null"`
)

// After
formatServerError(err)
expect(err.message).toMatchInlineSnapshot(`
"Class extends value undefined is not a constructor or null
This might be caused by a React Class Component being rendered in a Server Component, React Class Components only works in Client Components. Read more: https://nextjs.org/docs/messages/class-component-in-server-component"
`)

// After second
formatServerError(err)
expect(err.message).toMatchInlineSnapshot(`
"Class extends value undefined is not a constructor or null
This might be caused by a React Class Component being rendered in a Server Component, React Class Components only works in Client Components. Read more: https://nextjs.org/docs/messages/class-component-in-server-component"
`)
})
})
9 changes: 7 additions & 2 deletions packages/next/src/lib/format-server-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ const invalidServerComponentReactHooks = [
]

function setMessage(error: Error, message: string): void {
if (error.message === message) return
error.message = message
if (error.stack) {
const lines = error.stack.split('\n')
Expand All @@ -29,11 +28,17 @@ export function formatServerError(error: Error): void {
'Class extends value undefined is not a constructor or null'
)
) {
const addedMessage =
'This might be caused by a React Class Component being rendered in a Server Component, React Class Components only works in Client Components. Read more: https://nextjs.org/docs/messages/class-component-in-server-component'

// If this error instance already has the message, don't add it again
if (error.message.includes(addedMessage)) return

setMessage(
error,
`${error.message}
This might be caused by a React Class Component being rendered in a Server Component, React Class Components only works in Client Components. Read more: https://nextjs.org/docs/messages/class-component-in-server-component`
${addedMessage}`
)
return
}
Expand Down

0 comments on commit 3930e5e

Please sign in to comment.