hydration.spec.ts 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  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 input v-model with non-string value bindings', () => {
  818. const { container } = mountWithHydration(
  819. '<input type="checkbox" value="true">',
  820. () =>
  821. withDirectives(
  822. createVNode(
  823. 'input',
  824. { type: 'checkbox', 'true-value': true },
  825. null,
  826. PatchFlags.PROPS,
  827. ['true-value']
  828. ),
  829. [[vModelCheckbox, true]]
  830. )
  831. )
  832. expect((container.firstChild as any)._trueValue).toBe(true)
  833. })
  834. test('force hydrate select option with non-string value bindings', () => {
  835. const { container } = mountWithHydration(
  836. '<select><option :value="true">ok</option></select>',
  837. () =>
  838. h('select', [
  839. // hoisted because bound value is a constant...
  840. createVNode('option', { value: true }, null, -1 /* HOISTED */)
  841. ])
  842. )
  843. expect((container.firstChild!.firstChild as any)._value).toBe(true)
  844. })
  845. // #5728
  846. test('empty text node in slot', () => {
  847. const Comp = {
  848. render(this: any) {
  849. return renderSlot(this.$slots, 'default', {}, () => [
  850. createTextVNode('')
  851. ])
  852. }
  853. }
  854. const { container, vnode } = mountWithHydration('<!--[--><!--]-->', () =>
  855. h(Comp)
  856. )
  857. expect(container.childNodes.length).toBe(3)
  858. const text = container.childNodes[1]
  859. expect(text.nodeType).toBe(3)
  860. expect(vnode.el).toBe(container.childNodes[0])
  861. // component => slot fragment => text node
  862. expect((vnode as any).component?.subTree.children[0].el).toBe(text)
  863. })
  864. test('app.unmount()', async () => {
  865. const container = document.createElement('DIV')
  866. container.innerHTML = '<button></button>'
  867. const App = defineComponent({
  868. setup(_, { expose }) {
  869. const count = ref(0)
  870. expose({ count })
  871. return () =>
  872. h('button', {
  873. onClick: () => count.value++
  874. })
  875. }
  876. })
  877. const app = createSSRApp(App)
  878. const vm = app.mount(container)
  879. await nextTick()
  880. expect((container as any)._vnode).toBeDefined()
  881. // @ts-expect-error - expose()'d properties are not available on vm type
  882. expect(vm.count).toBe(0)
  883. app.unmount()
  884. expect((container as any)._vnode).toBe(null)
  885. })
  886. // #6637
  887. test('stringified root fragment', () => {
  888. mountWithHydration(`<!--[--><div></div><!--]-->`, () =>
  889. createStaticVNode(`<div></div>`, 1)
  890. )
  891. expect(`mismatch`).not.toHaveBeenWarned()
  892. })
  893. test('transition appear', () => {
  894. const { vnode, container } = mountWithHydration(
  895. `<template><div>foo</div></template>`,
  896. () =>
  897. h(
  898. Transition,
  899. { appear: true },
  900. {
  901. default: () => h('div', 'foo')
  902. }
  903. )
  904. )
  905. expect(container.firstChild).toMatchInlineSnapshot(`
  906. <div
  907. class="v-enter-from v-enter-active"
  908. >
  909. foo
  910. </div>
  911. `)
  912. expect(vnode.el).toBe(container.firstChild)
  913. expect(`mismatch`).not.toHaveBeenWarned()
  914. })
  915. test('transition appear with v-if', () => {
  916. const show = false
  917. const { vnode, container } = mountWithHydration(
  918. `<template><!----></template>`,
  919. () =>
  920. h(
  921. Transition,
  922. { appear: true },
  923. {
  924. default: () => (show ? h('div', 'foo') : createCommentVNode(''))
  925. }
  926. )
  927. )
  928. expect(container.firstChild).toMatchInlineSnapshot('<!---->')
  929. expect(vnode.el).toBe(container.firstChild)
  930. expect(`mismatch`).not.toHaveBeenWarned()
  931. })
  932. test('transition appear with v-show', () => {
  933. const show = false
  934. const { vnode, container } = mountWithHydration(
  935. `<template><div style="display: none;">foo</div></template>`,
  936. () =>
  937. h(
  938. Transition,
  939. { appear: true },
  940. {
  941. default: () =>
  942. withDirectives(createVNode('div', null, 'foo'), [[vShow, show]])
  943. }
  944. )
  945. )
  946. expect(container.firstChild).toMatchInlineSnapshot(`
  947. <div
  948. class="v-enter-from v-enter-active"
  949. style="display: none;"
  950. >
  951. foo
  952. </div>
  953. `)
  954. expect((container.firstChild as any)[vShowOldKey]).toBe('')
  955. expect(vnode.el).toBe(container.firstChild)
  956. expect(`mismatch`).not.toHaveBeenWarned()
  957. })
  958. describe('mismatch handling', () => {
  959. test('text node', () => {
  960. const { container } = mountWithHydration(`foo`, () => 'bar')
  961. expect(container.textContent).toBe('bar')
  962. expect(`Hydration text mismatch`).toHaveBeenWarned()
  963. })
  964. test('element text content', () => {
  965. const { container } = mountWithHydration(`<div>foo</div>`, () =>
  966. h('div', 'bar')
  967. )
  968. expect(container.innerHTML).toBe('<div>bar</div>')
  969. expect(`Hydration text content mismatch in <div>`).toHaveBeenWarned()
  970. })
  971. test('not enough children', () => {
  972. const { container } = mountWithHydration(`<div></div>`, () =>
  973. h('div', [h('span', 'foo'), h('span', 'bar')])
  974. )
  975. expect(container.innerHTML).toBe(
  976. '<div><span>foo</span><span>bar</span></div>'
  977. )
  978. expect(`Hydration children mismatch in <div>`).toHaveBeenWarned()
  979. })
  980. test('too many children', () => {
  981. const { container } = mountWithHydration(
  982. `<div><span>foo</span><span>bar</span></div>`,
  983. () => h('div', [h('span', 'foo')])
  984. )
  985. expect(container.innerHTML).toBe('<div><span>foo</span></div>')
  986. expect(`Hydration children mismatch in <div>`).toHaveBeenWarned()
  987. })
  988. test('complete mismatch', () => {
  989. const { container } = mountWithHydration(
  990. `<div><span>foo</span><span>bar</span></div>`,
  991. () => h('div', [h('div', 'foo'), h('p', 'bar')])
  992. )
  993. expect(container.innerHTML).toBe('<div><div>foo</div><p>bar</p></div>')
  994. expect(`Hydration node mismatch`).toHaveBeenWarnedTimes(2)
  995. })
  996. test('fragment mismatch removal', () => {
  997. const { container } = mountWithHydration(
  998. `<div><!--[--><div>foo</div><div>bar</div><!--]--></div>`,
  999. () => h('div', [h('span', 'replaced')])
  1000. )
  1001. expect(container.innerHTML).toBe('<div><span>replaced</span></div>')
  1002. expect(`Hydration node mismatch`).toHaveBeenWarned()
  1003. })
  1004. test('fragment not enough children', () => {
  1005. const { container } = mountWithHydration(
  1006. `<div><!--[--><div>foo</div><!--]--><div>baz</div></div>`,
  1007. () => h('div', [[h('div', 'foo'), h('div', 'bar')], h('div', 'baz')])
  1008. )
  1009. expect(container.innerHTML).toBe(
  1010. '<div><!--[--><div>foo</div><div>bar</div><!--]--><div>baz</div></div>'
  1011. )
  1012. expect(`Hydration node mismatch`).toHaveBeenWarned()
  1013. })
  1014. test('fragment too many children', () => {
  1015. const { container } = mountWithHydration(
  1016. `<div><!--[--><div>foo</div><div>bar</div><!--]--><div>baz</div></div>`,
  1017. () => h('div', [[h('div', 'foo')], h('div', 'baz')])
  1018. )
  1019. expect(container.innerHTML).toBe(
  1020. '<div><!--[--><div>foo</div><!--]--><div>baz</div></div>'
  1021. )
  1022. // fragment ends early and attempts to hydrate the extra <div>bar</div>
  1023. // as 2nd fragment child.
  1024. expect(`Hydration text content mismatch`).toHaveBeenWarned()
  1025. // excessive children removal
  1026. expect(`Hydration children mismatch`).toHaveBeenWarned()
  1027. })
  1028. test('Teleport target has empty children', () => {
  1029. const teleportContainer = document.createElement('div')
  1030. teleportContainer.id = 'teleport'
  1031. document.body.appendChild(teleportContainer)
  1032. mountWithHydration('<!--teleport start--><!--teleport end-->', () =>
  1033. h(Teleport, { to: '#teleport' }, [h('span', 'value')])
  1034. )
  1035. expect(teleportContainer.innerHTML).toBe(`<span>value</span>`)
  1036. expect(`Hydration children mismatch`).toHaveBeenWarned()
  1037. })
  1038. })
  1039. })