hydration.spec.ts 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  1. /**
  2. * @vitest-environment jsdom
  3. */
  4. import {
  5. createSSRApp,
  6. h,
  7. ref,
  8. nextTick,
  9. VNode,
  10. Teleport,
  11. createStaticVNode,
  12. Suspense,
  13. onMounted,
  14. defineAsyncComponent,
  15. defineComponent,
  16. createTextVNode,
  17. createVNode,
  18. withDirectives,
  19. vModelCheckbox,
  20. renderSlot,
  21. Transition,
  22. createCommentVNode,
  23. vShow
  24. } from '@vue/runtime-dom'
  25. import { renderToString, SSRContext } from '@vue/server-renderer'
  26. import { PatchFlags } from '@vue/shared'
  27. import { vShowOldKey } from '../../runtime-dom/src/directives/vShow'
  28. function mountWithHydration(html: string, render: () => any) {
  29. const container = document.createElement('div')
  30. container.innerHTML = html
  31. const app = createSSRApp({
  32. render
  33. })
  34. return {
  35. vnode: app.mount(container).$.subTree as VNode<Node, Element> & {
  36. el: Element
  37. },
  38. container
  39. }
  40. }
  41. const triggerEvent = (type: string, el: Element) => {
  42. const event = new Event(type)
  43. el.dispatchEvent(event)
  44. }
  45. describe('SSR hydration', () => {
  46. beforeEach(() => {
  47. document.body.innerHTML = ''
  48. })
  49. test('text', async () => {
  50. const msg = ref('foo')
  51. const { vnode, container } = mountWithHydration('foo', () => msg.value)
  52. expect(vnode.el).toBe(container.firstChild)
  53. expect(container.textContent).toBe('foo')
  54. msg.value = 'bar'
  55. await nextTick()
  56. expect(container.textContent).toBe('bar')
  57. })
  58. test('empty text', async () => {
  59. const { container } = mountWithHydration('<div></div>', () =>
  60. h('div', createTextVNode(''))
  61. )
  62. expect(container.textContent).toBe('')
  63. expect(`Hydration children mismatch in <div>`).not.toHaveBeenWarned()
  64. })
  65. test('comment', () => {
  66. const { vnode, container } = mountWithHydration('<!---->', () => null)
  67. expect(vnode.el).toBe(container.firstChild)
  68. expect(vnode.el.nodeType).toBe(8) // comment
  69. })
  70. test('static', () => {
  71. const html = '<div><span>hello</span></div>'
  72. const { vnode, container } = mountWithHydration(html, () =>
  73. createStaticVNode('', 1)
  74. )
  75. expect(vnode.el).toBe(container.firstChild)
  76. expect(vnode.el.outerHTML).toBe(html)
  77. expect(vnode.anchor).toBe(container.firstChild)
  78. expect(vnode.children).toBe(html)
  79. })
  80. test('static (multiple elements)', () => {
  81. const staticContent = '<div></div><span>hello</span>'
  82. const html = `<div><div>hi</div>` + staticContent + `<div>ho</div></div>`
  83. const n1 = h('div', 'hi')
  84. const s = createStaticVNode('', 2)
  85. const n2 = h('div', 'ho')
  86. const { container } = mountWithHydration(html, () => h('div', [n1, s, n2]))
  87. const div = container.firstChild!
  88. expect(n1.el).toBe(div.firstChild)
  89. expect(n2.el).toBe(div.lastChild)
  90. expect(s.el).toBe(div.childNodes[1])
  91. expect(s.anchor).toBe(div.childNodes[2])
  92. expect(s.children).toBe(staticContent)
  93. })
  94. // #6008
  95. test('static (with text node as starting node)', () => {
  96. const html = ` A <span>foo</span> B`
  97. const { vnode, container } = mountWithHydration(html, () =>
  98. createStaticVNode(` A <span>foo</span> B`, 3)
  99. )
  100. expect(vnode.el).toBe(container.firstChild)
  101. expect(vnode.anchor).toBe(container.lastChild)
  102. expect(`Hydration node mismatch`).not.toHaveBeenWarned()
  103. })
  104. test('static with content adoption', () => {
  105. const html = ` A <span>foo</span> B`
  106. const { vnode, container } = mountWithHydration(html, () =>
  107. createStaticVNode(``, 3)
  108. )
  109. expect(vnode.el).toBe(container.firstChild)
  110. expect(vnode.anchor).toBe(container.lastChild)
  111. expect(vnode.children).toBe(html)
  112. expect(`Hydration node mismatch`).not.toHaveBeenWarned()
  113. })
  114. test('element with text children', async () => {
  115. const msg = ref('foo')
  116. const { vnode, container } = mountWithHydration(
  117. '<div class="foo">foo</div>',
  118. () => h('div', { class: msg.value }, msg.value)
  119. )
  120. expect(vnode.el).toBe(container.firstChild)
  121. expect(container.firstChild!.textContent).toBe('foo')
  122. msg.value = 'bar'
  123. await nextTick()
  124. expect(container.innerHTML).toBe(`<div class="bar">bar</div>`)
  125. })
  126. test('element with elements children', async () => {
  127. const msg = ref('foo')
  128. const fn = vi.fn()
  129. const { vnode, container } = mountWithHydration(
  130. '<div><span>foo</span><span class="foo"></span></div>',
  131. () =>
  132. h('div', [
  133. h('span', msg.value),
  134. h('span', { class: msg.value, onClick: fn })
  135. ])
  136. )
  137. expect(vnode.el).toBe(container.firstChild)
  138. expect((vnode.children as VNode[])[0].el).toBe(
  139. container.firstChild!.childNodes[0]
  140. )
  141. expect((vnode.children as VNode[])[1].el).toBe(
  142. container.firstChild!.childNodes[1]
  143. )
  144. // event handler
  145. triggerEvent('click', vnode.el.querySelector('.foo')!)
  146. expect(fn).toHaveBeenCalled()
  147. msg.value = 'bar'
  148. await nextTick()
  149. expect(vnode.el.innerHTML).toBe(`<span>bar</span><span class="bar"></span>`)
  150. })
  151. test('element with ref', () => {
  152. const el = ref()
  153. const { vnode, container } = mountWithHydration('<div></div>', () =>
  154. h('div', { ref: el })
  155. )
  156. expect(vnode.el).toBe(container.firstChild)
  157. expect(el.value).toBe(vnode.el)
  158. })
  159. test('Fragment', async () => {
  160. const msg = ref('foo')
  161. const fn = vi.fn()
  162. const { vnode, container } = mountWithHydration(
  163. '<div><!--[--><span>foo</span><!--[--><span class="foo"></span><!--]--><!--]--></div>',
  164. () =>
  165. h('div', [
  166. [h('span', msg.value), [h('span', { class: msg.value, onClick: fn })]]
  167. ])
  168. )
  169. expect(vnode.el).toBe(container.firstChild)
  170. expect(vnode.el.innerHTML).toBe(
  171. `<!--[--><span>foo</span><!--[--><span class="foo"></span><!--]--><!--]-->`
  172. )
  173. // start fragment 1
  174. const fragment1 = (vnode.children as VNode[])[0]
  175. expect(fragment1.el).toBe(vnode.el.childNodes[0])
  176. const fragment1Children = fragment1.children as VNode[]
  177. // first <span>
  178. expect(fragment1Children[0].el!.tagName).toBe('SPAN')
  179. expect(fragment1Children[0].el).toBe(vnode.el.childNodes[1])
  180. // start fragment 2
  181. const fragment2 = fragment1Children[1]
  182. expect(fragment2.el).toBe(vnode.el.childNodes[2])
  183. const fragment2Children = fragment2.children as VNode[]
  184. // second <span>
  185. expect(fragment2Children[0].el!.tagName).toBe('SPAN')
  186. expect(fragment2Children[0].el).toBe(vnode.el.childNodes[3])
  187. // end fragment 2
  188. expect(fragment2.anchor).toBe(vnode.el.childNodes[4])
  189. // end fragment 1
  190. expect(fragment1.anchor).toBe(vnode.el.childNodes[5])
  191. // event handler
  192. triggerEvent('click', vnode.el.querySelector('.foo')!)
  193. expect(fn).toHaveBeenCalled()
  194. msg.value = 'bar'
  195. await nextTick()
  196. expect(vnode.el.innerHTML).toBe(
  197. `<!--[--><span>bar</span><!--[--><span class="bar"></span><!--]--><!--]-->`
  198. )
  199. })
  200. test('Teleport', async () => {
  201. const msg = ref('foo')
  202. const fn = vi.fn()
  203. const teleportContainer = document.createElement('div')
  204. teleportContainer.id = 'teleport'
  205. teleportContainer.innerHTML = `<span>foo</span><span class="foo"></span><!--teleport anchor-->`
  206. document.body.appendChild(teleportContainer)
  207. const { vnode, container } = mountWithHydration(
  208. '<!--teleport start--><!--teleport end-->',
  209. () =>
  210. h(Teleport, { to: '#teleport' }, [
  211. h('span', msg.value),
  212. h('span', { class: msg.value, onClick: fn })
  213. ])
  214. )
  215. expect(vnode.el).toBe(container.firstChild)
  216. expect(vnode.anchor).toBe(container.lastChild)
  217. expect(vnode.target).toBe(teleportContainer)
  218. expect((vnode.children as VNode[])[0].el).toBe(
  219. teleportContainer.childNodes[0]
  220. )
  221. expect((vnode.children as VNode[])[1].el).toBe(
  222. teleportContainer.childNodes[1]
  223. )
  224. expect(vnode.targetAnchor).toBe(teleportContainer.childNodes[2])
  225. // event handler
  226. triggerEvent('click', teleportContainer.querySelector('.foo')!)
  227. expect(fn).toHaveBeenCalled()
  228. msg.value = 'bar'
  229. await nextTick()
  230. expect(teleportContainer.innerHTML).toBe(
  231. `<span>bar</span><span class="bar"></span><!--teleport anchor-->`
  232. )
  233. })
  234. test('Teleport (multiple + integration)', async () => {
  235. const msg = ref('foo')
  236. const fn1 = vi.fn()
  237. const fn2 = vi.fn()
  238. const Comp = () => [
  239. h(Teleport, { to: '#teleport2' }, [
  240. h('span', msg.value),
  241. h('span', { class: msg.value, onClick: fn1 })
  242. ]),
  243. h(Teleport, { to: '#teleport2' }, [
  244. h('span', msg.value + '2'),
  245. h('span', { class: msg.value + '2', onClick: fn2 })
  246. ])
  247. ]
  248. const teleportContainer = document.createElement('div')
  249. teleportContainer.id = 'teleport2'
  250. const ctx: SSRContext = {}
  251. const mainHtml = await renderToString(h(Comp), ctx)
  252. expect(mainHtml).toMatchInlineSnapshot(
  253. `"<!--[--><!--teleport start--><!--teleport end--><!--teleport start--><!--teleport end--><!--]-->"`
  254. )
  255. const teleportHtml = ctx.teleports!['#teleport2']
  256. expect(teleportHtml).toMatchInlineSnapshot(
  257. `"<span>foo</span><span class="foo"></span><!--teleport anchor--><span>foo2</span><span class="foo2"></span><!--teleport anchor-->"`
  258. )
  259. teleportContainer.innerHTML = teleportHtml
  260. document.body.appendChild(teleportContainer)
  261. const { vnode, container } = mountWithHydration(mainHtml, Comp)
  262. expect(vnode.el).toBe(container.firstChild)
  263. const teleportVnode1 = (vnode.children as VNode[])[0]
  264. const teleportVnode2 = (vnode.children as VNode[])[1]
  265. expect(teleportVnode1.el).toBe(container.childNodes[1])
  266. expect(teleportVnode1.anchor).toBe(container.childNodes[2])
  267. expect(teleportVnode2.el).toBe(container.childNodes[3])
  268. expect(teleportVnode2.anchor).toBe(container.childNodes[4])
  269. expect(teleportVnode1.target).toBe(teleportContainer)
  270. expect((teleportVnode1 as any).children[0].el).toBe(
  271. teleportContainer.childNodes[0]
  272. )
  273. expect(teleportVnode1.targetAnchor).toBe(teleportContainer.childNodes[2])
  274. expect(teleportVnode2.target).toBe(teleportContainer)
  275. expect((teleportVnode2 as any).children[0].el).toBe(
  276. teleportContainer.childNodes[3]
  277. )
  278. expect(teleportVnode2.targetAnchor).toBe(teleportContainer.childNodes[5])
  279. // // event handler
  280. triggerEvent('click', teleportContainer.querySelector('.foo')!)
  281. expect(fn1).toHaveBeenCalled()
  282. triggerEvent('click', teleportContainer.querySelector('.foo2')!)
  283. expect(fn2).toHaveBeenCalled()
  284. msg.value = 'bar'
  285. await nextTick()
  286. expect(teleportContainer.innerHTML).toMatchInlineSnapshot(
  287. `"<span>bar</span><span class="bar"></span><!--teleport anchor--><span>bar2</span><span class="bar2"></span><!--teleport anchor-->"`
  288. )
  289. })
  290. test('Teleport (disabled)', async () => {
  291. const msg = ref('foo')
  292. const fn1 = vi.fn()
  293. const fn2 = vi.fn()
  294. const Comp = () => [
  295. h('div', 'foo'),
  296. h(Teleport, { to: '#teleport3', disabled: true }, [
  297. h('span', msg.value),
  298. h('span', { class: msg.value, onClick: fn1 })
  299. ]),
  300. h('div', { class: msg.value + '2', onClick: fn2 }, 'bar')
  301. ]
  302. const teleportContainer = document.createElement('div')
  303. teleportContainer.id = 'teleport3'
  304. const ctx: SSRContext = {}
  305. const mainHtml = await renderToString(h(Comp), ctx)
  306. expect(mainHtml).toMatchInlineSnapshot(
  307. `"<!--[--><div>foo</div><!--teleport start--><span>foo</span><span class="foo"></span><!--teleport end--><div class="foo2">bar</div><!--]-->"`
  308. )
  309. const teleportHtml = ctx.teleports!['#teleport3']
  310. expect(teleportHtml).toMatchInlineSnapshot(`"<!--teleport anchor-->"`)
  311. teleportContainer.innerHTML = teleportHtml
  312. document.body.appendChild(teleportContainer)
  313. const { vnode, container } = mountWithHydration(mainHtml, Comp)
  314. expect(vnode.el).toBe(container.firstChild)
  315. const children = vnode.children as VNode[]
  316. expect(children[0].el).toBe(container.childNodes[1])
  317. const teleportVnode = children[1]
  318. expect(teleportVnode.el).toBe(container.childNodes[2])
  319. expect((teleportVnode.children as VNode[])[0].el).toBe(
  320. container.childNodes[3]
  321. )
  322. expect((teleportVnode.children as VNode[])[1].el).toBe(
  323. container.childNodes[4]
  324. )
  325. expect(teleportVnode.anchor).toBe(container.childNodes[5])
  326. expect(children[2].el).toBe(container.childNodes[6])
  327. expect(teleportVnode.target).toBe(teleportContainer)
  328. expect(teleportVnode.targetAnchor).toBe(teleportContainer.childNodes[0])
  329. // // event handler
  330. triggerEvent('click', container.querySelector('.foo')!)
  331. expect(fn1).toHaveBeenCalled()
  332. triggerEvent('click', container.querySelector('.foo2')!)
  333. expect(fn2).toHaveBeenCalled()
  334. msg.value = 'bar'
  335. await nextTick()
  336. expect(container.innerHTML).toMatchInlineSnapshot(
  337. `"<!--[--><div>foo</div><!--teleport start--><span>bar</span><span class="bar"></span><!--teleport end--><div class="bar2">bar</div><!--]-->"`
  338. )
  339. })
  340. // #6152
  341. test('Teleport (disabled + as component root)', () => {
  342. const { container } = mountWithHydration(
  343. '<!--[--><div>Parent fragment</div><!--teleport start--><div>Teleport content</div><!--teleport end--><!--]-->',
  344. () => [
  345. h('div', 'Parent fragment'),
  346. h(() =>
  347. h(Teleport, { to: 'body', disabled: true }, [
  348. h('div', 'Teleport content')
  349. ])
  350. )
  351. ]
  352. )
  353. expect(document.body.innerHTML).toBe('')
  354. expect(container.innerHTML).toBe(
  355. '<!--[--><div>Parent fragment</div><!--teleport start--><div>Teleport content</div><!--teleport end--><!--]-->'
  356. )
  357. expect(
  358. `Hydration completed but contains mismatches.`
  359. ).not.toHaveBeenWarned()
  360. })
  361. test('Teleport (as component root)', () => {
  362. const teleportContainer = document.createElement('div')
  363. teleportContainer.id = 'teleport4'
  364. teleportContainer.innerHTML = `hello<!--teleport anchor-->`
  365. document.body.appendChild(teleportContainer)
  366. const wrapper = {
  367. render() {
  368. return h(Teleport, { to: '#teleport4' }, ['hello'])
  369. }
  370. }
  371. const { vnode, container } = mountWithHydration(
  372. '<div><!--teleport start--><!--teleport end--><div></div></div>',
  373. () => h('div', [h(wrapper), h('div')])
  374. )
  375. expect(vnode.el).toBe(container.firstChild)
  376. // component el
  377. const wrapperVNode = (vnode as any).children[0]
  378. const tpStart = container.firstChild?.firstChild
  379. const tpEnd = tpStart?.nextSibling
  380. expect(wrapperVNode.el).toBe(tpStart)
  381. expect(wrapperVNode.component.subTree.el).toBe(tpStart)
  382. expect(wrapperVNode.component.subTree.anchor).toBe(tpEnd)
  383. // next node hydrate properly
  384. const nextVNode = (vnode as any).children[1]
  385. expect(nextVNode.el).toBe(container.firstChild?.lastChild)
  386. })
  387. test('Teleport (nested)', () => {
  388. const teleportContainer = document.createElement('div')
  389. teleportContainer.id = 'teleport5'
  390. teleportContainer.innerHTML = `<div><!--teleport start--><!--teleport end--></div><!--teleport anchor--><div>child</div><!--teleport anchor-->`
  391. document.body.appendChild(teleportContainer)
  392. const { vnode, container } = mountWithHydration(
  393. '<!--teleport start--><!--teleport end-->',
  394. () =>
  395. h(Teleport, { to: '#teleport5' }, [
  396. h('div', [h(Teleport, { to: '#teleport5' }, [h('div', 'child')])])
  397. ])
  398. )
  399. expect(vnode.el).toBe(container.firstChild)
  400. expect(vnode.anchor).toBe(container.lastChild)
  401. const childDivVNode = (vnode as any).children[0]
  402. const div = teleportContainer.firstChild
  403. expect(childDivVNode.el).toBe(div)
  404. expect(vnode.targetAnchor).toBe(div?.nextSibling)
  405. const childTeleportVNode = childDivVNode.children[0]
  406. expect(childTeleportVNode.el).toBe(div?.firstChild)
  407. expect(childTeleportVNode.anchor).toBe(div?.lastChild)
  408. expect(childTeleportVNode.targetAnchor).toBe(teleportContainer.lastChild)
  409. expect(childTeleportVNode.children[0].el).toBe(
  410. teleportContainer.lastChild?.previousSibling
  411. )
  412. })
  413. // compile SSR + client render fn from the same template & hydrate
  414. test('full compiler integration', async () => {
  415. const mounted: string[] = []
  416. const log = vi.fn()
  417. const toggle = ref(true)
  418. const Child = {
  419. data() {
  420. return {
  421. count: 0,
  422. text: 'hello',
  423. style: {
  424. color: 'red'
  425. }
  426. }
  427. },
  428. mounted() {
  429. mounted.push('child')
  430. },
  431. template: `
  432. <div>
  433. <span class="count" :style="style">{{ count }}</span>
  434. <button class="inc" @click="count++">inc</button>
  435. <button class="change" @click="style.color = 'green'" >change color</button>
  436. <button class="emit" @click="$emit('foo')">emit</button>
  437. <span class="text">{{ text }}</span>
  438. <input v-model="text">
  439. </div>
  440. `
  441. }
  442. const App = {
  443. setup() {
  444. return { toggle }
  445. },
  446. mounted() {
  447. mounted.push('parent')
  448. },
  449. template: `
  450. <div>
  451. <span>hello</span>
  452. <template v-if="toggle">
  453. <Child @foo="log('child')"/>
  454. <template v-if="true">
  455. <button class="parent-click" @click="log('click')">click me</button>
  456. </template>
  457. </template>
  458. <span>hello</span>
  459. </div>`,
  460. components: {
  461. Child
  462. },
  463. methods: {
  464. log
  465. }
  466. }
  467. const container = document.createElement('div')
  468. // server render
  469. container.innerHTML = await renderToString(h(App))
  470. // hydrate
  471. createSSRApp(App).mount(container)
  472. // assert interactions
  473. // 1. parent button click
  474. triggerEvent('click', container.querySelector('.parent-click')!)
  475. expect(log).toHaveBeenCalledWith('click')
  476. // 2. child inc click + text interpolation
  477. const count = container.querySelector('.count') as HTMLElement
  478. expect(count.textContent).toBe(`0`)
  479. triggerEvent('click', container.querySelector('.inc')!)
  480. await nextTick()
  481. expect(count.textContent).toBe(`1`)
  482. // 3. child color click + style binding
  483. expect(count.style.color).toBe('red')
  484. triggerEvent('click', container.querySelector('.change')!)
  485. await nextTick()
  486. expect(count.style.color).toBe('green')
  487. // 4. child event emit
  488. triggerEvent('click', container.querySelector('.emit')!)
  489. expect(log).toHaveBeenCalledWith('child')
  490. // 5. child v-model
  491. const text = container.querySelector('.text')!
  492. const input = container.querySelector('input')!
  493. expect(text.textContent).toBe('hello')
  494. input.value = 'bye'
  495. triggerEvent('input', input)
  496. await nextTick()
  497. expect(text.textContent).toBe('bye')
  498. })
  499. test('handle click error in ssr mode', async () => {
  500. const App = {
  501. setup() {
  502. const throwError = () => {
  503. throw new Error('Sentry Error')
  504. }
  505. return { throwError }
  506. },
  507. template: `
  508. <div>
  509. <button class="parent-click" @click="throwError">click me</button>
  510. </div>`
  511. }
  512. const container = document.createElement('div')
  513. // server render
  514. container.innerHTML = await renderToString(h(App))
  515. // hydrate
  516. const app = createSSRApp(App)
  517. const handler = (app.config.errorHandler = vi.fn())
  518. app.mount(container)
  519. // assert interactions
  520. // parent button click
  521. triggerEvent('click', container.querySelector('.parent-click')!)
  522. expect(handler).toHaveBeenCalled()
  523. })
  524. test('handle blur error in ssr mode', async () => {
  525. const App = {
  526. setup() {
  527. const throwError = () => {
  528. throw new Error('Sentry Error')
  529. }
  530. return { throwError }
  531. },
  532. template: `
  533. <div>
  534. <input class="parent-click" @blur="throwError"/>
  535. </div>`
  536. }
  537. const container = document.createElement('div')
  538. // server render
  539. container.innerHTML = await renderToString(h(App))
  540. // hydrate
  541. const app = createSSRApp(App)
  542. const handler = (app.config.errorHandler = vi.fn())
  543. app.mount(container)
  544. // assert interactions
  545. // parent blur event
  546. triggerEvent('blur', container.querySelector('.parent-click')!)
  547. expect(handler).toHaveBeenCalled()
  548. })
  549. test('Suspense', async () => {
  550. const AsyncChild = {
  551. async setup() {
  552. const count = ref(0)
  553. return () =>
  554. h(
  555. 'span',
  556. {
  557. onClick: () => {
  558. count.value++
  559. }
  560. },
  561. count.value
  562. )
  563. }
  564. }
  565. const { vnode, container } = mountWithHydration('<span>0</span>', () =>
  566. h(Suspense, () => h(AsyncChild))
  567. )
  568. expect(vnode.el).toBe(container.firstChild)
  569. // wait for hydration to finish
  570. await new Promise(r => setTimeout(r))
  571. triggerEvent('click', container.querySelector('span')!)
  572. await nextTick()
  573. expect(container.innerHTML).toBe(`<span>1</span>`)
  574. })
  575. test('Suspense (full integration)', async () => {
  576. const mountedCalls: number[] = []
  577. const asyncDeps: Promise<any>[] = []
  578. const AsyncChild = defineComponent({
  579. props: ['n'],
  580. async setup(props) {
  581. const count = ref(props.n)
  582. onMounted(() => {
  583. mountedCalls.push(props.n)
  584. })
  585. const p = new Promise(r => setTimeout(r, props.n * 10))
  586. asyncDeps.push(p)
  587. await p
  588. return () =>
  589. h(
  590. 'span',
  591. {
  592. onClick: () => {
  593. count.value++
  594. }
  595. },
  596. count.value
  597. )
  598. }
  599. })
  600. const done = vi.fn()
  601. const App = {
  602. template: `
  603. <Suspense @resolve="done">
  604. <div>
  605. <AsyncChild :n="1" />
  606. <AsyncChild :n="2" />
  607. </div>
  608. </Suspense>`,
  609. components: {
  610. AsyncChild
  611. },
  612. methods: {
  613. done
  614. }
  615. }
  616. const container = document.createElement('div')
  617. // server render
  618. container.innerHTML = await renderToString(h(App))
  619. expect(container.innerHTML).toMatchInlineSnapshot(
  620. `"<div><span>1</span><span>2</span></div>"`
  621. )
  622. // reset asyncDeps from ssr
  623. asyncDeps.length = 0
  624. // hydrate
  625. createSSRApp(App).mount(container)
  626. expect(mountedCalls.length).toBe(0)
  627. expect(asyncDeps.length).toBe(2)
  628. // wait for hydration to complete
  629. await Promise.all(asyncDeps)
  630. await new Promise(r => setTimeout(r))
  631. // should flush buffered effects
  632. expect(mountedCalls).toMatchObject([1, 2])
  633. expect(container.innerHTML).toMatch(
  634. `<div><span>1</span><span>2</span></div>`
  635. )
  636. const span1 = container.querySelector('span')!
  637. triggerEvent('click', span1)
  638. await nextTick()
  639. expect(container.innerHTML).toMatch(
  640. `<div><span>2</span><span>2</span></div>`
  641. )
  642. const span2 = span1.nextSibling as Element
  643. triggerEvent('click', span2)
  644. await nextTick()
  645. expect(container.innerHTML).toMatch(
  646. `<div><span>2</span><span>3</span></div>`
  647. )
  648. })
  649. test('async component', async () => {
  650. const spy = vi.fn()
  651. const Comp = () =>
  652. h(
  653. 'button',
  654. {
  655. onClick: spy
  656. },
  657. 'hello!'
  658. )
  659. let serverResolve: any
  660. let AsyncComp = defineAsyncComponent(
  661. () =>
  662. new Promise(r => {
  663. serverResolve = r
  664. })
  665. )
  666. const App = {
  667. render() {
  668. return ['hello', h(AsyncComp), 'world']
  669. }
  670. }
  671. // server render
  672. const htmlPromise = renderToString(h(App))
  673. serverResolve(Comp)
  674. const html = await htmlPromise
  675. expect(html).toMatchInlineSnapshot(
  676. `"<!--[-->hello<button>hello!</button>world<!--]-->"`
  677. )
  678. // hydration
  679. let clientResolve: any
  680. AsyncComp = defineAsyncComponent(
  681. () =>
  682. new Promise(r => {
  683. clientResolve = r
  684. })
  685. )
  686. const container = document.createElement('div')
  687. container.innerHTML = html
  688. createSSRApp(App).mount(container)
  689. // hydration not complete yet
  690. triggerEvent('click', container.querySelector('button')!)
  691. expect(spy).not.toHaveBeenCalled()
  692. // resolve
  693. clientResolve(Comp)
  694. await new Promise(r => setTimeout(r))
  695. // should be hydrated now
  696. triggerEvent('click', container.querySelector('button')!)
  697. expect(spy).toHaveBeenCalled()
  698. })
  699. test('update async wrapper before resolve', async () => {
  700. const Comp = {
  701. render() {
  702. return h('h1', 'Async component')
  703. }
  704. }
  705. let serverResolve: any
  706. let AsyncComp = defineAsyncComponent(
  707. () =>
  708. new Promise(r => {
  709. serverResolve = r
  710. })
  711. )
  712. const bol = ref(true)
  713. const App = {
  714. setup() {
  715. onMounted(() => {
  716. // change state, this makes updateComponent(AsyncComp) execute before
  717. // the async component is resolved
  718. bol.value = false
  719. })
  720. return () => {
  721. return [bol.value ? 'hello' : 'world', h(AsyncComp)]
  722. }
  723. }
  724. }
  725. // server render
  726. const htmlPromise = renderToString(h(App))
  727. serverResolve(Comp)
  728. const html = await htmlPromise
  729. expect(html).toMatchInlineSnapshot(
  730. `"<!--[-->hello<h1>Async component</h1><!--]-->"`
  731. )
  732. // hydration
  733. let clientResolve: any
  734. AsyncComp = defineAsyncComponent(
  735. () =>
  736. new Promise(r => {
  737. clientResolve = r
  738. })
  739. )
  740. const container = document.createElement('div')
  741. container.innerHTML = html
  742. createSSRApp(App).mount(container)
  743. // resolve
  744. clientResolve(Comp)
  745. await new Promise(r => setTimeout(r))
  746. // should be hydrated now
  747. expect(`Hydration node mismatch`).not.toHaveBeenWarned()
  748. expect(container.innerHTML).toMatchInlineSnapshot(
  749. `"<!--[-->world<h1>Async component</h1><!--]-->"`
  750. )
  751. })
  752. // #3787
  753. test('unmount async wrapper before load', async () => {
  754. let resolve: any
  755. const AsyncComp = defineAsyncComponent(
  756. () =>
  757. new Promise(r => {
  758. resolve = r
  759. })
  760. )
  761. const show = ref(true)
  762. const root = document.createElement('div')
  763. root.innerHTML = '<div><div>async</div></div>'
  764. createSSRApp({
  765. render() {
  766. return h('div', [show.value ? h(AsyncComp) : h('div', 'hi')])
  767. }
  768. }).mount(root)
  769. show.value = false
  770. await nextTick()
  771. expect(root.innerHTML).toBe('<div><div>hi</div></div>')
  772. resolve({})
  773. })
  774. test('unmount async wrapper before load (fragment)', async () => {
  775. let resolve: any
  776. const AsyncComp = defineAsyncComponent(
  777. () =>
  778. new Promise(r => {
  779. resolve = r
  780. })
  781. )
  782. const show = ref(true)
  783. const root = document.createElement('div')
  784. root.innerHTML = '<div><!--[-->async<!--]--></div>'
  785. createSSRApp({
  786. render() {
  787. return h('div', [show.value ? h(AsyncComp) : h('div', 'hi')])
  788. }
  789. }).mount(root)
  790. show.value = false
  791. await nextTick()
  792. expect(root.innerHTML).toBe('<div><div>hi</div></div>')
  793. resolve({})
  794. })
  795. test('elements with camel-case in svg ', () => {
  796. const { vnode, container } = mountWithHydration(
  797. '<animateTransform></animateTransform>',
  798. () => h('animateTransform')
  799. )
  800. expect(vnode.el).toBe(container.firstChild)
  801. expect(`Hydration node mismatch`).not.toHaveBeenWarned()
  802. })
  803. test('SVG as a mount container', () => {
  804. const svgContainer = document.createElement('svg')
  805. svgContainer.innerHTML = '<g></g>'
  806. const app = createSSRApp({
  807. render: () => h('g')
  808. })
  809. expect(
  810. (
  811. app.mount(svgContainer).$.subTree as VNode<Node, Element> & {
  812. el: Element
  813. }
  814. ).el instanceof SVGElement
  815. )
  816. })
  817. test('force hydrate prop with `.prop` modifier', () => {
  818. const { container } = mountWithHydration(
  819. '<input type="checkbox" :indeterminate.prop="true">',
  820. () =>
  821. h('input', {
  822. type: 'checkbox',
  823. '.indeterminate': true
  824. })
  825. )
  826. expect((container.firstChild! as any).indeterminate).toBe(true)
  827. })
  828. test('force hydrate input v-model with non-string value bindings', () => {
  829. const { container } = mountWithHydration(
  830. '<input type="checkbox" value="true">',
  831. () =>
  832. withDirectives(
  833. createVNode(
  834. 'input',
  835. { type: 'checkbox', 'true-value': true },
  836. null,
  837. PatchFlags.PROPS,
  838. ['true-value']
  839. ),
  840. [[vModelCheckbox, true]]
  841. )
  842. )
  843. expect((container.firstChild as any)._trueValue).toBe(true)
  844. })
  845. test('force hydrate checkbox with indeterminate', () => {
  846. const { container } = mountWithHydration(
  847. '<input type="checkbox" indeterminate>',
  848. () =>
  849. createVNode(
  850. 'input',
  851. { type: 'checkbox', indeterminate: '' },
  852. null,
  853. PatchFlags.HOISTED
  854. )
  855. )
  856. expect((container.firstChild as any).indeterminate).toBe(true)
  857. })
  858. test('force hydrate select option with non-string value bindings', () => {
  859. const { container } = mountWithHydration(
  860. '<select><option :value="true">ok</option></select>',
  861. () =>
  862. h('select', [
  863. // hoisted because bound value is a constant...
  864. createVNode('option', { value: true }, null, -1 /* HOISTED */)
  865. ])
  866. )
  867. expect((container.firstChild!.firstChild as any)._value).toBe(true)
  868. })
  869. // #5728
  870. test('empty text node in slot', () => {
  871. const Comp = {
  872. render(this: any) {
  873. return renderSlot(this.$slots, 'default', {}, () => [
  874. createTextVNode('')
  875. ])
  876. }
  877. }
  878. const { container, vnode } = mountWithHydration('<!--[--><!--]-->', () =>
  879. h(Comp)
  880. )
  881. expect(container.childNodes.length).toBe(3)
  882. const text = container.childNodes[1]
  883. expect(text.nodeType).toBe(3)
  884. expect(vnode.el).toBe(container.childNodes[0])
  885. // component => slot fragment => text node
  886. expect((vnode as any).component?.subTree.children[0].el).toBe(text)
  887. })
  888. test('app.unmount()', async () => {
  889. const container = document.createElement('DIV')
  890. container.innerHTML = '<button></button>'
  891. const App = defineComponent({
  892. setup(_, { expose }) {
  893. const count = ref(0)
  894. expose({ count })
  895. return () =>
  896. h('button', {
  897. onClick: () => count.value++
  898. })
  899. }
  900. })
  901. const app = createSSRApp(App)
  902. const vm = app.mount(container)
  903. await nextTick()
  904. expect((container as any)._vnode).toBeDefined()
  905. // @ts-expect-error - expose()'d properties are not available on vm type
  906. expect(vm.count).toBe(0)
  907. app.unmount()
  908. expect((container as any)._vnode).toBe(null)
  909. })
  910. // #6637
  911. test('stringified root fragment', () => {
  912. mountWithHydration(`<!--[--><div></div><!--]-->`, () =>
  913. createStaticVNode(`<div></div>`, 1)
  914. )
  915. expect(`mismatch`).not.toHaveBeenWarned()
  916. })
  917. test('transition appear', () => {
  918. const { vnode, container } = mountWithHydration(
  919. `<template><div>foo</div></template>`,
  920. () =>
  921. h(
  922. Transition,
  923. { appear: true },
  924. {
  925. default: () => h('div', 'foo')
  926. }
  927. )
  928. )
  929. expect(container.firstChild).toMatchInlineSnapshot(`
  930. <div
  931. class="v-enter-from v-enter-active"
  932. >
  933. foo
  934. </div>
  935. `)
  936. expect(vnode.el).toBe(container.firstChild)
  937. expect(`mismatch`).not.toHaveBeenWarned()
  938. })
  939. test('transition appear with v-if', () => {
  940. const show = false
  941. const { vnode, container } = mountWithHydration(
  942. `<template><!----></template>`,
  943. () =>
  944. h(
  945. Transition,
  946. { appear: true },
  947. {
  948. default: () => (show ? h('div', 'foo') : createCommentVNode(''))
  949. }
  950. )
  951. )
  952. expect(container.firstChild).toMatchInlineSnapshot('<!---->')
  953. expect(vnode.el).toBe(container.firstChild)
  954. expect(`mismatch`).not.toHaveBeenWarned()
  955. })
  956. test('transition appear with v-show', () => {
  957. const show = false
  958. const { vnode, container } = mountWithHydration(
  959. `<template><div style="display: none;">foo</div></template>`,
  960. () =>
  961. h(
  962. Transition,
  963. { appear: true },
  964. {
  965. default: () =>
  966. withDirectives(createVNode('div', null, 'foo'), [[vShow, show]])
  967. }
  968. )
  969. )
  970. expect(container.firstChild).toMatchInlineSnapshot(`
  971. <div
  972. class="v-enter-from v-enter-active"
  973. style="display: none;"
  974. >
  975. foo
  976. </div>
  977. `)
  978. expect((container.firstChild as any)[vShowOldKey]).toBe('')
  979. expect(vnode.el).toBe(container.firstChild)
  980. expect(`mismatch`).not.toHaveBeenWarned()
  981. })
  982. test('transition appear w/ event listener', async () => {
  983. const container = document.createElement('div')
  984. container.innerHTML = `<template><button>0</button></template>`
  985. createSSRApp({
  986. data() {
  987. return {
  988. count: 0
  989. }
  990. },
  991. template: `
  992. <Transition appear>
  993. <button @click="count++">{{count}}</button>
  994. </Transition>
  995. `
  996. }).mount(container)
  997. expect(container.firstChild).toMatchInlineSnapshot(`
  998. <button
  999. class="v-enter-from v-enter-active"
  1000. >
  1001. 0
  1002. </button>
  1003. `)
  1004. triggerEvent('click', container.querySelector('button')!)
  1005. await nextTick()
  1006. expect(container.firstChild).toMatchInlineSnapshot(`
  1007. <button
  1008. class="v-enter-from v-enter-active"
  1009. >
  1010. 1
  1011. </button>
  1012. `)
  1013. })
  1014. describe('mismatch handling', () => {
  1015. test('text node', () => {
  1016. const { container } = mountWithHydration(`foo`, () => 'bar')
  1017. expect(container.textContent).toBe('bar')
  1018. expect(`Hydration text mismatch`).toHaveBeenWarned()
  1019. })
  1020. test('element text content', () => {
  1021. const { container } = mountWithHydration(`<div>foo</div>`, () =>
  1022. h('div', 'bar')
  1023. )
  1024. expect(container.innerHTML).toBe('<div>bar</div>')
  1025. expect(`Hydration text content mismatch in <div>`).toHaveBeenWarned()
  1026. })
  1027. test('not enough children', () => {
  1028. const { container } = mountWithHydration(`<div></div>`, () =>
  1029. h('div', [h('span', 'foo'), h('span', 'bar')])
  1030. )
  1031. expect(container.innerHTML).toBe(
  1032. '<div><span>foo</span><span>bar</span></div>'
  1033. )
  1034. expect(`Hydration children mismatch in <div>`).toHaveBeenWarned()
  1035. })
  1036. test('too many children', () => {
  1037. const { container } = mountWithHydration(
  1038. `<div><span>foo</span><span>bar</span></div>`,
  1039. () => h('div', [h('span', 'foo')])
  1040. )
  1041. expect(container.innerHTML).toBe('<div><span>foo</span></div>')
  1042. expect(`Hydration children mismatch in <div>`).toHaveBeenWarned()
  1043. })
  1044. test('complete mismatch', () => {
  1045. const { container } = mountWithHydration(
  1046. `<div><span>foo</span><span>bar</span></div>`,
  1047. () => h('div', [h('div', 'foo'), h('p', 'bar')])
  1048. )
  1049. expect(container.innerHTML).toBe('<div><div>foo</div><p>bar</p></div>')
  1050. expect(`Hydration node mismatch`).toHaveBeenWarnedTimes(2)
  1051. })
  1052. test('fragment mismatch removal', () => {
  1053. const { container } = mountWithHydration(
  1054. `<div><!--[--><div>foo</div><div>bar</div><!--]--></div>`,
  1055. () => h('div', [h('span', 'replaced')])
  1056. )
  1057. expect(container.innerHTML).toBe('<div><span>replaced</span></div>')
  1058. expect(`Hydration node mismatch`).toHaveBeenWarned()
  1059. })
  1060. test('fragment not enough children', () => {
  1061. const { container } = mountWithHydration(
  1062. `<div><!--[--><div>foo</div><!--]--><div>baz</div></div>`,
  1063. () => h('div', [[h('div', 'foo'), h('div', 'bar')], h('div', 'baz')])
  1064. )
  1065. expect(container.innerHTML).toBe(
  1066. '<div><!--[--><div>foo</div><div>bar</div><!--]--><div>baz</div></div>'
  1067. )
  1068. expect(`Hydration node mismatch`).toHaveBeenWarned()
  1069. })
  1070. test('fragment too many children', () => {
  1071. const { container } = mountWithHydration(
  1072. `<div><!--[--><div>foo</div><div>bar</div><!--]--><div>baz</div></div>`,
  1073. () => h('div', [[h('div', 'foo')], h('div', 'baz')])
  1074. )
  1075. expect(container.innerHTML).toBe(
  1076. '<div><!--[--><div>foo</div><!--]--><div>baz</div></div>'
  1077. )
  1078. // fragment ends early and attempts to hydrate the extra <div>bar</div>
  1079. // as 2nd fragment child.
  1080. expect(`Hydration text content mismatch`).toHaveBeenWarned()
  1081. // excessive children removal
  1082. expect(`Hydration children mismatch`).toHaveBeenWarned()
  1083. })
  1084. test('Teleport target has empty children', () => {
  1085. const teleportContainer = document.createElement('div')
  1086. teleportContainer.id = 'teleport'
  1087. document.body.appendChild(teleportContainer)
  1088. mountWithHydration('<!--teleport start--><!--teleport end-->', () =>
  1089. h(Teleport, { to: '#teleport' }, [h('span', 'value')])
  1090. )
  1091. expect(teleportContainer.innerHTML).toBe(`<span>value</span>`)
  1092. expect(`Hydration children mismatch`).toHaveBeenWarned()
  1093. })
  1094. test('comment mismatch (element)', () => {
  1095. const { container } = mountWithHydration(`<div><span></span></div>`, () =>
  1096. h('div', [createCommentVNode('hi')])
  1097. )
  1098. expect(container.innerHTML).toBe('<div><!--hi--></div>')
  1099. expect(`Hydration node mismatch`).toHaveBeenWarned()
  1100. })
  1101. test('comment mismatch (text)', () => {
  1102. const { container } = mountWithHydration(`<div>foobar</div>`, () =>
  1103. h('div', [createCommentVNode('hi')])
  1104. )
  1105. expect(container.innerHTML).toBe('<div><!--hi--></div>')
  1106. expect(`Hydration node mismatch`).toHaveBeenWarned()
  1107. })
  1108. })
  1109. })