Skip to content
Myr

components.test.tsx

This file

Path

src/jsx/components.test.tsx

936 lines 路 27.2 KiB 路 TypeScript

Last changed by

Merge commit from forkTaku Amanobefore adoption2b8ed40

History of this file

Take it

1/* eslint-disable @typescript-eslint/no-explicit-any */2/** @jsxImportSource ./ */3import { JSDOM } from 'jsdom'4import { raw } from '../helper/html'5import type { HtmlEscapedString } from '../utils/html'6import { HtmlEscapedCallbackPhase, resolveCallback as rawResolveCallback } from '../utils/html'7import { ErrorBoundary } from './components'8import { Suspense, renderToReadableStream, StreamingContext } from './streaming'910const unsafeHtml = '<img src=x onerror=alert(1)>'11const escapedUnsafeHtml = '&lt;img src=x onerror=alert(1)&gt;'1213function resolveCallback(template: string | HtmlEscapedString) {14  return rawResolveCallback(template, HtmlEscapedCallbackPhase.Stream, false, {})15}1617function replacementResult(html: string) {18  const document = new JSDOM(html, { runScripts: 'dangerously' }).window.document19  document.querySelectorAll('template, script').forEach((e) => e.remove())20  return document.body.innerHTML21}2223async function stringify(node: { toString(): string | Promise<string> }): Promise<string> {24  return String(25    await rawResolveCallback(await node.toString(), HtmlEscapedCallbackPhase.Stringify, false, {})26  )27}2829async function drainStream(stream: ReadableStream<Uint8Array>): Promise<string> {30  const decoder = new TextDecoder()31  let result = ''32  for await (const chunk of stream) {33    result += decoder.decode(chunk)34  }35  return result36}3738const Fallback = () => <div>Out Of Service</div>3940describe('ErrorBoundary', () => {41  let errorBoundaryCounter = 042  let suspenseCounter = 043  afterEach(() => {44    errorBoundaryCounter++45    suspenseCounter++46  })4748  describe('sync', async () => {49    const Component = ({ error }: { error?: boolean }) => {50      if (error) {51        throw new Error('Error')52      }53      return <div>Hello</div>54    }5556    it('no error', async () => {57      const html = (58        <ErrorBoundary fallback={<Fallback />}>59          <Component />60        </ErrorBoundary>61      )6263      expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')6465      errorBoundaryCounter--66      suspenseCounter--67    })6869    it('error', async () => {70      const html = (71        <ErrorBoundary fallback={<Fallback />}>72          <Component error={true} />73        </ErrorBoundary>74      )7576      expect((await resolveCallback(await html.toString())).toString()).toEqual(77        '<div>Out Of Service</div>'78      )7980      suspenseCounter--81    })8283    it('nullish', async () => {84      const html = (85        <div>86          <ErrorBoundary fallback={<Fallback />}>{[null, undefined]}</ErrorBoundary>87        </div>88      )8990      expect((await resolveCallback(await html.toString())).toString()).toEqual('<div></div>')9192      errorBoundaryCounter--93      suspenseCounter--94    })9596    it('boolean', async () => {97      const html = (98        <div>99          <ErrorBoundary fallback={<Fallback />}>{[true, false]}</ErrorBoundary>100        </div>101      )102103      expect((await resolveCallback(await html.toString())).toString()).toEqual('<div></div>')104105      errorBoundaryCounter--106      suspenseCounter--107    })108109    it('string content', async () => {110      const html = <ErrorBoundary fallback={<Fallback />}>{'< ok >'}</ErrorBoundary>111112      expect((await resolveCallback(await html.toString())).toString()).toEqual('&lt; ok &gt;')113114      errorBoundaryCounter--115      suspenseCounter--116    })117118    it('error: string content', async () => {119      const html = (120        <ErrorBoundary fallback={'< error >'}>121          <Component error={true} />122        </ErrorBoundary>123      )124125      expect((await resolveCallback(await html.toString())).toString()).toEqual('&lt; error &gt;')126127      errorBoundaryCounter--128      suspenseCounter--129    })130131    it('error: Promise<string> from fallback', async () => {132      const html = (133        <ErrorBoundary fallback={Promise.resolve('< error >')}>134          <Component error={true} />135        </ErrorBoundary>136      )137138      expect((await resolveCallback(await html.toString())).toString()).toEqual('&lt; error &gt;')139140      errorBoundaryCounter--141      suspenseCounter--142    })143144    it('error: string content from fallbackRender', async () => {145      const html = (146        <ErrorBoundary fallbackRender={() => '< error >'}>147          <Component error={true} />148        </ErrorBoundary>149      )150151      expect((await resolveCallback(await html.toString())).toString()).toEqual('&lt; error &gt;')152153      errorBoundaryCounter--154      suspenseCounter--155    })156157    it('error: Promise<string> from fallbackRender', async () => {158      const html = (159        <ErrorBoundary fallbackRender={() => Promise.resolve('< error >')}>160          <Component error={true} />161        </ErrorBoundary>162      )163164      expect((await resolveCallback(await html.toString())).toString()).toEqual('&lt; error &gt;')165166      errorBoundaryCounter--167      suspenseCounter--168    })169  })170171  describe('async', async () => {172    const Component = async ({ error }: { error?: boolean }) => {173      await new Promise((resolve) => setTimeout(resolve, 10))174      if (error) {175        throw new Error('Error')176      }177      return <div>Hello</div>178    }179180    it('no error', async () => {181      const html = (182        <ErrorBoundary fallback={<Fallback />}>183          <Component />184        </ErrorBoundary>185      )186187      expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')188189      errorBoundaryCounter--190      suspenseCounter--191    })192193    it('error', async () => {194      const html = (195        <ErrorBoundary fallback={<Fallback />}>196          <Component error={true} />197        </ErrorBoundary>198      )199200      expect((await resolveCallback(await html.toString())).toString()).toEqual(201        '<div>Out Of Service</div>'202      )203204      suspenseCounter--205    })206207    it('error: string content', async () => {208      const html = (209        <ErrorBoundary fallback={'< error >'}>210          <Component error={true} />211        </ErrorBoundary>212      )213214      expect((await resolveCallback(await html.toString())).toString()).toEqual('&lt; error &gt;')215216      suspenseCounter--217    })218219    it('error: Promise<string> from fallback', async () => {220      const html = (221        <ErrorBoundary fallback={Promise.resolve('< error >')}>222          <Component error={true} />223        </ErrorBoundary>224      )225226      expect((await resolveCallback(await html.toString())).toString()).toEqual('&lt; error &gt;')227228      suspenseCounter--229    })230231    it('error: string content from fallbackRender', async () => {232      const html = (233        <ErrorBoundary fallbackRender={() => '< error >'}>234          <Component error={true} />235        </ErrorBoundary>236      )237238      expect((await resolveCallback(await html.toString())).toString()).toEqual('&lt; error &gt;')239240      suspenseCounter--241    })242243    it('error: Promise<string> from fallbackRender', async () => {244      const html = (245        <ErrorBoundary fallbackRender={() => Promise.resolve('< error >')}>246          <Component error={true} />247        </ErrorBoundary>248      )249250      expect((await resolveCallback(await html.toString())).toString()).toEqual('&lt; error &gt;')251252      suspenseCounter--253    })254  })255256  describe('async : nested', async () => {257    const handlers: Record<number, { resolve: (value: unknown) => void; reject: () => void }> = {}258    const Component = async ({ id }: { id: number }) => {259      await new Promise((resolve, reject) => (handlers[id] = { resolve, reject }))260      return <div>{id}</div>261    }262263    it('no error', async () => {264      const html = (265        <ErrorBoundary fallback={<Fallback />}>266          <Component id={1} />267          <ErrorBoundary fallback={<Fallback />}>268            <Component id={2} />269          </ErrorBoundary>270        </ErrorBoundary>271      ).toString()272273      Object.values(handlers).forEach(({ resolve }) => resolve(undefined))274275      expect((await resolveCallback(await html)).toString()).toEqual('<div>1</div><div>2</div>')276277      errorBoundaryCounter++278      suspenseCounter--279    })280281    it('error in parent', async () => {282      const html = (283        <ErrorBoundary fallback={<Fallback />}>284          <Component id={1} />285          <ErrorBoundary fallback={<Fallback />}>286            <Component id={2} />287          </ErrorBoundary>288        </ErrorBoundary>289      ).toString()290291      handlers[2].resolve(undefined)292      handlers[1].reject()293294      expect((await resolveCallback(await html)).toString()).toEqual('<div>Out Of Service</div>')295296      errorBoundaryCounter++297      suspenseCounter--298    })299300    it('error in child', async () => {301      const html = (302        <ErrorBoundary fallback={<Fallback />}>303          <Component id={1} />304          <ErrorBoundary fallback={<Fallback />}>305            <Component id={2} />306          </ErrorBoundary>307        </ErrorBoundary>308      ).toString()309310      handlers[1].resolve(undefined)311      handlers[2].reject()312313      expect((await resolveCallback(await html)).toString()).toEqual(314        '<div>1</div><div>Out Of Service</div>'315      )316317      errorBoundaryCounter++318      suspenseCounter--319    })320  })321322  describe('async : setTimeout', async () => {323    const TimeoutSuccessComponent = async () => {324      await new Promise((resolve) => setTimeout(resolve, 10))325      return <div>OK</div>326    }327    const TimeoutErrorComponent = async () => {328      await new Promise((resolve) => setTimeout(resolve, 0))329      throw new Error('Error')330    }331332    it('fallback', async () => {333      const html = (334        <>335          <TimeoutSuccessComponent />336          <ErrorBoundary fallback={<Fallback />}>337            <TimeoutErrorComponent />338          </ErrorBoundary>339        </>340      ).toString()341342      expect((await resolveCallback(await html)).toString()).toEqual(343        '<div>OK</div><div>Out Of Service</div>'344      )345346      suspenseCounter--347    })348  })349350  describe('streaming', async () => {351    const Component = async ({ error }: { error?: boolean }) => {352      await new Promise((resolve) => setTimeout(resolve, 10))353      if (error) {354        throw new Error('Error')355      }356      return <div>Hello</div>357    }358359    it('no error', async () => {360      const stream = renderToReadableStream(361        <ErrorBoundary fallback={<Fallback />}>362          <Suspense fallback={<p>Loading...</p>}>363            <Component />364          </Suspense>365        </ErrorBoundary>366      )367      const chunks = []368      const textDecoder = new TextDecoder()369      for await (const chunk of stream as any) {370        chunks.push(textDecoder.decode(chunk))371      }372373      expect(chunks).toEqual([374        `<template id="E:${errorBoundaryCounter}"></template><!--E:${errorBoundaryCounter}-->`,375        `<template data-hono-target="E:${errorBoundaryCounter}"><template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$--></template><script>376((d,c) => {377c=d.currentScript.previousSibling378d=d.getElementById('E:${errorBoundaryCounter}')379if(!d)return380d.parentElement.insertBefore(c.content,d.nextSibling)381})(document)382</script>`,383        `<template data-hono-target="H:${suspenseCounter}"><div>Hello</div></template><script>384((d,c,n) => {385c=d.currentScript.previousSibling386d=d.getElementById('H:${suspenseCounter}')387if(!d)return388do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')389d.replaceWith(c.content)390})(document)391</script><script>392((d,c,n) => {393d=d.getElementById('E:${errorBoundaryCounter}')394if(!d)return395n=d.nextSibling396while(n.nodeType!=8||n.nodeValue!='E:${errorBoundaryCounter}'){n=n.nextSibling}397n.remove()398d.remove()399})(document)400</script>`,401      ])402403      expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(404        '<div>Hello</div>'405      )406    })407408    it('with StreamingContext', async () => {409      const stream = renderToReadableStream(410        <StreamingContext value={{ scriptNonce: 'test-nonce' }}>411          <ErrorBoundary fallback={<Fallback />}>412            <Suspense fallback={<p>Loading...</p>}>413              <Component />414            </Suspense>415          </ErrorBoundary>416        </StreamingContext>417      )418      const chunks = []419      const textDecoder = new TextDecoder()420      for await (const chunk of stream as any) {421        chunks.push(textDecoder.decode(chunk))422      }423424      expect(chunks).toEqual([425        `<template id="E:${errorBoundaryCounter}"></template><!--E:${errorBoundaryCounter}-->`,426        `<template data-hono-target="E:${errorBoundaryCounter}"><template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$--></template><script nonce="test-nonce">427((d,c) => {428c=d.currentScript.previousSibling429d=d.getElementById('E:${errorBoundaryCounter}')430if(!d)return431d.parentElement.insertBefore(c.content,d.nextSibling)432})(document)433</script>`,434        `<template data-hono-target="H:${suspenseCounter}"><div>Hello</div></template><script nonce="test-nonce">435((d,c,n) => {436c=d.currentScript.previousSibling437d=d.getElementById('H:${suspenseCounter}')438if(!d)return439do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')440d.replaceWith(c.content)441})(document)442</script><script>443((d,c,n) => {444d=d.getElementById('E:${errorBoundaryCounter}')445if(!d)return446n=d.nextSibling447while(n.nodeType!=8||n.nodeValue!='E:${errorBoundaryCounter}'){n=n.nextSibling}448n.remove()449d.remove()450})(document)451</script>`,452      ])453454      expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(455        '<div>Hello</div>'456      )457    })458459    it('error', async () => {460      const html = (461        <ErrorBoundary fallback={<Fallback />}>462          <Component error={true} />463        </ErrorBoundary>464      )465466      expect((await resolveCallback(await html.toString())).toString()).toEqual(467        '<div>Out Of Service</div>'468      )469    })470  })471472  describe('streaming : contains multiple suspense', async () => {473    const handlers: Record<number, { resolve: (value: unknown) => void; reject: () => void }> = {}474    const Component = async ({ id }: { id: number }) => {475      await new Promise((resolve, reject) => (handlers[id] = { resolve, reject }))476      return <div>{id}</div>477    }478479    it('no error', async () => {480      const stream = renderToReadableStream(481        <ErrorBoundary fallback={<Fallback />}>482          <Suspense fallback={<p>Loading...</p>}>483            <Component id={1} />484          </Suspense>485          <Suspense fallback={<p>Loading...</p>}>486            <Component id={2} />487          </Suspense>488          <Suspense fallback={<p>Loading...</p>}>489            <Component id={3} />490          </Suspense>491        </ErrorBoundary>492      )493494      Object.values(handlers).forEach(({ resolve }) => resolve(undefined))495496      const chunks = []497      const textDecoder = new TextDecoder()498      for await (const chunk of stream as any) {499        chunks.push(textDecoder.decode(chunk))500      }501502      expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(503        '<div>1</div><div>2</div><div>3</div>'504      )505    })506507    it('error', async () => {508      const stream = renderToReadableStream(509        <ErrorBoundary fallback={<Fallback />}>510          <Suspense fallback={<p>Loading...</p>}>511            <Component id={1} />512          </Suspense>513          <Suspense fallback={<p>Loading...</p>}>514            <Component id={2} />515          </Suspense>516          <Suspense fallback={<p>Loading...</p>}>517            <Component id={3} />518          </Suspense>519        </ErrorBoundary>520      )521522      handlers[1].resolve(undefined)523      handlers[2].resolve(undefined)524      handlers[3].reject()525526      const chunks = []527      const textDecoder = new TextDecoder()528      for await (const chunk of stream as any) {529        chunks.push(textDecoder.decode(chunk))530      }531532      expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(533        '<div>Out Of Service</div>'534      )535    })536537    it('renders fallback and reports error once when multiple children reject', async () => {538      let fallbackRenderCount = 0539      let onErrorCount = 0540      const stream = renderToReadableStream(541        <ErrorBoundary542          fallbackRender={() => {543            fallbackRenderCount++544            return <Fallback />545          }}546          onError={() => {547            onErrorCount++548          }}549        >550          <Suspense fallback={<p>Loading...</p>}>551            <Component id={1} />552          </Suspense>553          <Suspense fallback={<p>Loading...</p>}>554            <Component id={2} />555          </Suspense>556          <Suspense fallback={<p>Loading...</p>}>557            <Component id={3} />558          </Suspense>559        </ErrorBoundary>560      )561562      handlers[1].reject()563      handlers[2].reject()564      handlers[3].resolve(undefined)565566      const chunks = []567      const textDecoder = new TextDecoder()568      for await (const chunk of stream as any) {569        chunks.push(textDecoder.decode(chunk))570      }571572      expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(573        '<div>Out Of Service</div>'574      )575      expect(fallbackRenderCount).toBe(1)576      expect(onErrorCount).toBe(1)577    })578579    it('preserves callbacks from a thenable fallback', async () => {580      const fallback = Promise.resolve(581        raw('<span>Recovering</span>', [582          ({ phase }) =>583            phase === HtmlEscapedCallbackPhase.Stream584              ? Promise.resolve('<span>Recovered</span>')585              : undefined,586        ])587      )588      const stream = renderToReadableStream(589        <ErrorBoundary fallback={fallback}>590          <Suspense fallback={<p>Loading...</p>}>591            <Component id={1} />592          </Suspense>593        </ErrorBoundary>594      )595596      handlers[1].reject()597598      const chunks = []599      const textDecoder = new TextDecoder()600      for await (const chunk of stream as any) {601        chunks.push(textDecoder.decode(chunk))602      }603604      expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(605        '<span>Recovering</span><span>Recovered</span>'606      )607    })608609    it('waits for an in-flight async fallback when multiple children reject', async () => {610      let resolveFallback!: (value: HtmlEscapedString | PromiseLike<HtmlEscapedString>) => void611      const fallback = new Promise<HtmlEscapedString>((resolve) => {612        resolveFallback = resolve613      })614615      const stream = renderToReadableStream(616        <ErrorBoundary fallback={fallback}>617          <Suspense fallback={<p>Loading...</p>}>618            <Component id={1} />619          </Suspense>620          <Suspense fallback={<p>Loading...</p>}>621            <Component id={2} />622          </Suspense>623          <Suspense fallback={<p>Loading...</p>}>624            <Component id={3} />625          </Suspense>626        </ErrorBoundary>627      )628629      handlers[1].reject()630      handlers[2].reject()631      handlers[3].resolve(undefined)632      await Promise.resolve()633      resolveFallback(<Fallback />)634635      const chunks = []636      const textDecoder = new TextDecoder()637      for await (const chunk of stream as any) {638        chunks.push(textDecoder.decode(chunk))639      }640641      expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(642        '<div>Out Of Service</div>'643      )644    })645  })646647  describe('streaming : nested', async () => {648    const handlers: Record<number, { resolve: (value: unknown) => void; reject: () => void }> = {}649    const Component = async ({ id }: { id: number }) => {650      await new Promise((resolve, reject) => (handlers[id] = { resolve, reject }))651      return <div>{id}</div>652    }653654    it('no error', async () => {655      const stream = renderToReadableStream(656        <ErrorBoundary fallback={<Fallback />}>657          <Suspense fallback={<p>Loading...</p>}>658            <Component id={1} />659          </Suspense>660          <ErrorBoundary fallback={<Fallback />}>661            <Suspense fallback={<p>Loading...</p>}>662              <Component id={2} />663            </Suspense>664          </ErrorBoundary>665        </ErrorBoundary>666      )667668      Object.values(handlers).forEach(({ resolve }) => resolve(undefined))669670      const chunks = []671      const textDecoder = new TextDecoder()672      for await (const chunk of stream as any) {673        chunks.push(textDecoder.decode(chunk))674      }675676      expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(677        '<div>1</div><div>2</div>'678      )679    })680681    it('error in parent', async () => {682      const stream = renderToReadableStream(683        <ErrorBoundary fallback={<Fallback />}>684          <Suspense fallback={<p>Loading...</p>}>685            <Component id={1} />686          </Suspense>687          <ErrorBoundary fallback={<Fallback />}>688            <Suspense fallback={<p>Loading...</p>}>689              <Component id={2} />690            </Suspense>691          </ErrorBoundary>692        </ErrorBoundary>693      )694695      handlers[2].resolve(undefined)696      handlers[1].reject()697698      const chunks = []699      const textDecoder = new TextDecoder()700      for await (const chunk of stream as any) {701        chunks.push(textDecoder.decode(chunk))702      }703704      expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(705        '<div>Out Of Service</div>'706      )707    })708709    it('error in child', async () => {710      const stream = renderToReadableStream(711        <ErrorBoundary fallback={<Fallback />}>712          <Suspense fallback={<p>Loading...</p>}>713            <Component id={1} />714          </Suspense>715          <ErrorBoundary fallback={<Fallback />}>716            <Suspense fallback={<p>Loading...</p>}>717              <Component id={2} />718            </Suspense>719          </ErrorBoundary>720        </ErrorBoundary>721      )722723      handlers[1].resolve(undefined)724      handlers[2].reject()725726      const chunks = []727      const textDecoder = new TextDecoder()728      for await (const chunk of stream as any) {729        chunks.push(textDecoder.decode(chunk))730      }731732      expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(733        '<div>1</div><div>Out Of Service</div>'734      )735    })736  })737738  describe('onError', async () => {739    const Component = ({ error }: { error?: boolean }) => {740      if (error) {741        throw new Error('Error')742      }743      return <div>Hello</div>744    }745746    it('no error', async () => {747      const errors: Error[] = []748      const html = (749        <ErrorBoundary fallback={<Fallback />} onError={(err) => errors.push(err)}>750          <Component />751        </ErrorBoundary>752      )753754      expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')755756      errorBoundaryCounter--757      suspenseCounter--758759      expect(errors).toEqual([])760    })761762    it('error', async () => {763      const errors: Error[] = []764      const html = (765        <ErrorBoundary fallback={<Fallback />} onError={(err) => errors.push(err)}>766          <Component error={true} />767        </ErrorBoundary>768      )769770      expect((await resolveCallback(await html.toString())).toString()).toEqual(771        '<div>Out Of Service</div>'772      )773774      suspenseCounter--775776      expect(errors[0]).toEqual(new Error('Error'))777    })778  })779780  describe('fallbackRender', async () => {781    const fallbackRenderer = (error: Error) => <div data-error>{error.message}</div>782    const Component = ({ error }: { error?: boolean }) => {783      if (error) {784        throw new Error('Error')785      }786      return <div>Hello</div>787    }788789    it('no error', async () => {790      const errors: Error[] = []791      const html = (792        <ErrorBoundary fallbackRender={fallbackRenderer}>793          <Component />794        </ErrorBoundary>795      )796797      expect((await resolveCallback(await html.toString())).toString()).toEqual('<div>Hello</div>')798799      errorBoundaryCounter--800      suspenseCounter--801802      expect(errors).toEqual([])803    })804805    it('error', async () => {806      const html = (807        <ErrorBoundary fallbackRender={fallbackRenderer}>808          <Component error={true} />809        </ErrorBoundary>810      )811812      expect((await resolveCallback(await html.toString())).toString()).toEqual(813        '<div data-error="true">Error</div>'814      )815816      suspenseCounter--817    })818  })819820  describe('escaping', () => {821    const Broken = () => {822      throw new Error('boom')823    }824825    it('escapes strings when an asynchronous sibling is present', async () => {826      const Async = async () => <span>done</span>827      const node = (828        <ErrorBoundary fallback='error'>829          {unsafeHtml}830          <Async />831        </ErrorBoundary>832      )833834      expect(await stringify(node)).toBe(`${escapedUnsafeHtml}<span>done</span>`)835      const streamed = await drainStream(renderToReadableStream(node))836      expect(streamed).toContain(escapedUnsafeHtml)837      expect(streamed).not.toContain(unsafeHtml)838    })839840    it('escapes untrusted object fallbacks', async () => {841      const object = { toString: () => unsafeHtml }842      const asyncObject = { toString: async () => unsafeHtml }843      const rawObject = { toString: () => raw(unsafeHtml) }844845      for (const fallback of [object, asyncObject, rawObject]) {846        expect(847          await stringify(848            <ErrorBoundary fallback={fallback as never}>849              <Broken />850            </ErrorBoundary>851          )852        ).toBe(escapedUnsafeHtml)853      }854    })855856    it('preserves an explicitly trusted fallback', async () => {857      expect(858        await stringify(859          <ErrorBoundary fallback={raw('<strong>trusted</strong>')}>860            <Broken />861          </ErrorBoundary>862        )863      ).toBe('<strong>trusted</strong>')864    })865866    it('does not interpret replacement patterns in content', async () => {867      const content = "literal $& $` $'"868      const Async = async () => <span>done</span>869870      expect(871        await stringify(872          <ErrorBoundary fallback='error'>873            {content}874            <Async />875          </ErrorBoundary>876        )877      ).toBe('literal $&amp; $` $&#39;<span>done</span>')878    })879880    it('escapes untrusted object children', async () => {881      const object = { toString: () => unsafeHtml }882      const asyncObject = { toString: async () => unsafeHtml }883      const rawObject = { toString: () => raw(unsafeHtml) }884885      for (const child of [object, asyncObject, rawObject]) {886        const node = <ErrorBoundary fallback='error'>{child as never}</ErrorBoundary>887        expect(await stringify(node)).toBe(escapedUnsafeHtml)888        const streamed = await drainStream(renderToReadableStream(node))889        expect(streamed).toContain(escapedUnsafeHtml)890        expect(streamed).not.toContain(unsafeHtml)891      }892    })893894    it('preserves explicitly trusted children', async () => {895      expect(896        await stringify(897          <ErrorBoundary fallback='error'>{raw('<strong>trusted</strong>')}</ErrorBoundary>898        )899      ).toBe('<strong>trusted</strong>')900    })901902    it('keeps benign object stringification visible', async () => {903      expect(await stringify(<ErrorBoundary fallback='error'>{{} as never}</ErrorBoundary>)).toBe(904        '[object Object]'905      )906    })907908    it('escapes nested fallback arrays', async () => {909      expect(910        await stringify(911          <ErrorBoundary fallback={[[unsafeHtml]]}>912            <Broken />913          </ErrorBoundary>914        )915      ).toBe(escapedUnsafeHtml)916    })917918    it('keeps the existing falsy fallbackRender behavior', async () => {919      expect(920        await stringify(921          <ErrorBoundary fallbackRender={() => 0}>922            <Broken />923          </ErrorBoundary>924        )925      ).toBe('')926    })927928    it('keeps a direct Promise child unchanged', async () => {929      expect(930        await stringify(931          <ErrorBoundary fallback='error'>{Promise.resolve('resolved')}</ErrorBoundary>932        )933      ).toBe('[object Promise]')934    })935  })936})