hydration.spec.ts 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779
  1. /**
  2. * @vitest-environment jsdom
  3. */
  4. import {
  5. type ObjectDirective,
  6. Suspense,
  7. Teleport,
  8. Transition,
  9. type VNode,
  10. createBlock,
  11. createCommentVNode,
  12. createElementBlock,
  13. createElementVNode,
  14. createSSRApp,
  15. createStaticVNode,
  16. createTextVNode,
  17. createVNode,
  18. defineAsyncComponent,
  19. defineComponent,
  20. h,
  21. nextTick,
  22. onMounted,
  23. openBlock,
  24. reactive,
  25. ref,
  26. renderSlot,
  27. useCssVars,
  28. vModelCheckbox,
  29. vShow,
  30. withCtx,
  31. withDirectives,
  32. } from '@vue/runtime-dom'
  33. import { type SSRContext, renderToString } from '@vue/server-renderer'
  34. import { PatchFlags, normalizeStyle } from '@vue/shared'
  35. import { vShowOriginalDisplay } from '../../runtime-dom/src/directives/vShow'
  36. import { expect } from 'vitest'
  37. function mountWithHydration(html: string, render: () => any) {
  38. const container = document.createElement('div')
  39. container.innerHTML = html
  40. const app = createSSRApp({
  41. render,
  42. })
  43. return {
  44. vnode: app.mount(container).$.subTree as VNode<Node, Element> & {
  45. el: Element
  46. },
  47. container,
  48. }
  49. }
  50. const triggerEvent = (type: string, el: Element) => {
  51. const event = new Event(type)
  52. el.dispatchEvent(event)
  53. }
  54. describe('SSR hydration', () => {
  55. beforeEach(() => {
  56. document.body.innerHTML = ''
  57. })
  58. test('text', async () => {
  59. const msg = ref('foo')
  60. const { vnode, container } = mountWithHydration('foo', () => msg.value)
  61. expect(vnode.el).toBe(container.firstChild)
  62. expect(container.textContent).toBe('foo')
  63. msg.value = 'bar'
  64. await nextTick()
  65. expect(container.textContent).toBe('bar')
  66. })
  67. test('empty text', async () => {
  68. const { container } = mountWithHydration('<div></div>', () =>
  69. h('div', createTextVNode('')),
  70. )
  71. expect(container.textContent).toBe('')
  72. expect(`Hydration children mismatch in <div>`).not.toHaveBeenWarned()
  73. })
  74. test('comment', () => {
  75. const { vnode, container } = mountWithHydration('<!---->', () => null)
  76. expect(vnode.el).toBe(container.firstChild)
  77. expect(vnode.el.nodeType).toBe(8) // comment
  78. })
  79. test('static', () => {
  80. const html = '<div><span>hello</span></div>'
  81. const { vnode, container } = mountWithHydration(html, () =>
  82. createStaticVNode('', 1),
  83. )
  84. expect(vnode.el).toBe(container.firstChild)
  85. expect(vnode.el.outerHTML).toBe(html)
  86. expect(vnode.anchor).toBe(container.firstChild)
  87. expect(vnode.children).toBe(html)
  88. })
  89. test('static (multiple elements)', () => {
  90. const staticContent = '<div></div><span>hello</span>'
  91. const html = `<div><div>hi</div>` + staticContent + `<div>ho</div></div>`
  92. const n1 = h('div', 'hi')
  93. const s = createStaticVNode('', 2)
  94. const n2 = h('div', 'ho')
  95. const { container } = mountWithHydration(html, () => h('div', [n1, s, n2]))
  96. const div = container.firstChild!
  97. expect(n1.el).toBe(div.firstChild)
  98. expect(n2.el).toBe(div.lastChild)
  99. expect(s.el).toBe(div.childNodes[1])
  100. expect(s.anchor).toBe(div.childNodes[2])
  101. expect(s.children).toBe(staticContent)
  102. })
  103. // #6008
  104. test('static (with text node as starting node)', () => {
  105. const html = ` A <span>foo</span> B`
  106. const { vnode, container } = mountWithHydration(html, () =>
  107. createStaticVNode(` A <span>foo</span> B`, 3),
  108. )
  109. expect(vnode.el).toBe(container.firstChild)
  110. expect(vnode.anchor).toBe(container.lastChild)
  111. expect(`Hydration node mismatch`).not.toHaveBeenWarned()
  112. })
  113. test('static with content adoption', () => {
  114. const html = ` A <span>foo</span> B`
  115. const { vnode, container } = mountWithHydration(html, () =>
  116. createStaticVNode(``, 3),
  117. )
  118. expect(vnode.el).toBe(container.firstChild)
  119. expect(vnode.anchor).toBe(container.lastChild)
  120. expect(vnode.children).toBe(html)
  121. expect(`Hydration node mismatch`).not.toHaveBeenWarned()
  122. })
  123. test('element with text children', async () => {
  124. const msg = ref('foo')
  125. const { vnode, container } = mountWithHydration(
  126. '<div class="foo">foo</div>',
  127. () => h('div', { class: msg.value }, msg.value),
  128. )
  129. expect(vnode.el).toBe(container.firstChild)
  130. expect(container.firstChild!.textContent).toBe('foo')
  131. msg.value = 'bar'
  132. await nextTick()
  133. expect(container.innerHTML).toBe(`<div class="bar">bar</div>`)
  134. })
  135. // #7285
  136. test('element with multiple continuous text vnodes', async () => {
  137. // should no mismatch warning
  138. const { container } = mountWithHydration('<div>fooo</div>', () =>
  139. h('div', ['fo', createTextVNode('o'), 'o']),
  140. )
  141. expect(container.textContent).toBe('fooo')
  142. })
  143. test('element with elements children', async () => {
  144. const msg = ref('foo')
  145. const fn = vi.fn()
  146. const { vnode, container } = mountWithHydration(
  147. '<div><span>foo</span><span class="foo"></span></div>',
  148. () =>
  149. h('div', [
  150. h('span', msg.value),
  151. h('span', { class: msg.value, onClick: fn }),
  152. ]),
  153. )
  154. expect(vnode.el).toBe(container.firstChild)
  155. expect((vnode.children as VNode[])[0].el).toBe(
  156. container.firstChild!.childNodes[0],
  157. )
  158. expect((vnode.children as VNode[])[1].el).toBe(
  159. container.firstChild!.childNodes[1],
  160. )
  161. // event handler
  162. triggerEvent('click', vnode.el.querySelector('.foo')!)
  163. expect(fn).toHaveBeenCalled()
  164. msg.value = 'bar'
  165. await nextTick()
  166. expect(vnode.el.innerHTML).toBe(`<span>bar</span><span class="bar"></span>`)
  167. })
  168. test('element with ref', () => {
  169. const el = ref()
  170. const { vnode, container } = mountWithHydration('<div></div>', () =>
  171. h('div', { ref: el }),
  172. )
  173. expect(vnode.el).toBe(container.firstChild)
  174. expect(el.value).toBe(vnode.el)
  175. })
  176. test('Fragment', async () => {
  177. const msg = ref('foo')
  178. const fn = vi.fn()
  179. const { vnode, container } = mountWithHydration(
  180. '<div><!--[--><span>foo</span><!--[--><span class="foo"></span><!--]--><!--]--></div>',
  181. () =>
  182. h('div', [
  183. [
  184. h('span', msg.value),
  185. [h('span', { class: msg.value, onClick: fn })],
  186. ],
  187. ]),
  188. )
  189. expect(vnode.el).toBe(container.firstChild)
  190. expect(vnode.el.innerHTML).toBe(
  191. `<!--[--><span>foo</span><!--[--><span class="foo"></span><!--]--><!--]-->`,
  192. )
  193. // start fragment 1
  194. const fragment1 = (vnode.children as VNode[])[0]
  195. expect(fragment1.el).toBe(vnode.el.childNodes[0])
  196. const fragment1Children = fragment1.children as VNode[]
  197. // first <span>
  198. expect(fragment1Children[0].el!.tagName).toBe('SPAN')
  199. expect(fragment1Children[0].el).toBe(vnode.el.childNodes[1])
  200. // start fragment 2
  201. const fragment2 = fragment1Children[1]
  202. expect(fragment2.el).toBe(vnode.el.childNodes[2])
  203. const fragment2Children = fragment2.children as VNode[]
  204. // second <span>
  205. expect(fragment2Children[0].el!.tagName).toBe('SPAN')
  206. expect(fragment2Children[0].el).toBe(vnode.el.childNodes[3])
  207. // end fragment 2
  208. expect(fragment2.anchor).toBe(vnode.el.childNodes[4])
  209. // end fragment 1
  210. expect(fragment1.anchor).toBe(vnode.el.childNodes[5])
  211. // event handler
  212. triggerEvent('click', vnode.el.querySelector('.foo')!)
  213. expect(fn).toHaveBeenCalled()
  214. msg.value = 'bar'
  215. await nextTick()
  216. expect(vnode.el.innerHTML).toBe(
  217. `<!--[--><span>bar</span><!--[--><span class="bar"></span><!--]--><!--]-->`,
  218. )
  219. })
  220. // #7285
  221. test('Fragment (multiple continuous text vnodes)', async () => {
  222. // should no mismatch warning
  223. const { container } = mountWithHydration('<!--[-->fooo<!--]-->', () => [
  224. 'fo',
  225. createTextVNode('o'),
  226. 'o',
  227. ])
  228. expect(container.textContent).toBe('fooo')
  229. })
  230. test('Teleport', async () => {
  231. const msg = ref('foo')
  232. const fn = vi.fn()
  233. const teleportContainer = document.createElement('div')
  234. teleportContainer.id = 'teleport'
  235. teleportContainer.innerHTML = `<span>foo</span><span class="foo"></span><!--teleport anchor-->`
  236. document.body.appendChild(teleportContainer)
  237. const { vnode, container } = mountWithHydration(
  238. '<!--teleport start--><!--teleport end-->',
  239. () =>
  240. h(Teleport, { to: '#teleport' }, [
  241. h('span', msg.value),
  242. h('span', { class: msg.value, onClick: fn }),
  243. ]),
  244. )
  245. expect(vnode.el).toBe(container.firstChild)
  246. expect(vnode.anchor).toBe(container.lastChild)
  247. expect(vnode.target).toBe(teleportContainer)
  248. expect((vnode.children as VNode[])[0].el).toBe(
  249. teleportContainer.childNodes[0],
  250. )
  251. expect((vnode.children as VNode[])[1].el).toBe(
  252. teleportContainer.childNodes[1],
  253. )
  254. expect(vnode.targetAnchor).toBe(teleportContainer.childNodes[2])
  255. // event handler
  256. triggerEvent('click', teleportContainer.querySelector('.foo')!)
  257. expect(fn).toHaveBeenCalled()
  258. msg.value = 'bar'
  259. await nextTick()
  260. expect(teleportContainer.innerHTML).toBe(
  261. `<span>bar</span><span class="bar"></span><!--teleport anchor-->`,
  262. )
  263. })
  264. test('Teleport (multiple + integration)', async () => {
  265. const msg = ref('foo')
  266. const fn1 = vi.fn()
  267. const fn2 = vi.fn()
  268. const Comp = () => [
  269. h(Teleport, { to: '#teleport2' }, [
  270. h('span', msg.value),
  271. h('span', { class: msg.value, onClick: fn1 }),
  272. ]),
  273. h(Teleport, { to: '#teleport2' }, [
  274. h('span', msg.value + '2'),
  275. h('span', { class: msg.value + '2', onClick: fn2 }),
  276. ]),
  277. ]
  278. const teleportContainer = document.createElement('div')
  279. teleportContainer.id = 'teleport2'
  280. const ctx: SSRContext = {}
  281. const mainHtml = await renderToString(h(Comp), ctx)
  282. expect(mainHtml).toMatchInlineSnapshot(
  283. `"<!--[--><!--teleport start--><!--teleport end--><!--teleport start--><!--teleport end--><!--]-->"`,
  284. )
  285. const teleportHtml = ctx.teleports!['#teleport2']
  286. expect(teleportHtml).toMatchInlineSnapshot(
  287. `"<span>foo</span><span class="foo"></span><!--teleport anchor--><span>foo2</span><span class="foo2"></span><!--teleport anchor-->"`,
  288. )
  289. teleportContainer.innerHTML = teleportHtml
  290. document.body.appendChild(teleportContainer)
  291. const { vnode, container } = mountWithHydration(mainHtml, Comp)
  292. expect(vnode.el).toBe(container.firstChild)
  293. const teleportVnode1 = (vnode.children as VNode[])[0]
  294. const teleportVnode2 = (vnode.children as VNode[])[1]
  295. expect(teleportVnode1.el).toBe(container.childNodes[1])
  296. expect(teleportVnode1.anchor).toBe(container.childNodes[2])
  297. expect(teleportVnode2.el).toBe(container.childNodes[3])
  298. expect(teleportVnode2.anchor).toBe(container.childNodes[4])
  299. expect(teleportVnode1.target).toBe(teleportContainer)
  300. expect((teleportVnode1 as any).children[0].el).toBe(
  301. teleportContainer.childNodes[0],
  302. )
  303. expect(teleportVnode1.targetAnchor).toBe(teleportContainer.childNodes[2])
  304. expect(teleportVnode2.target).toBe(teleportContainer)
  305. expect((teleportVnode2 as any).children[0].el).toBe(
  306. teleportContainer.childNodes[3],
  307. )
  308. expect(teleportVnode2.targetAnchor).toBe(teleportContainer.childNodes[5])
  309. // // event handler
  310. triggerEvent('click', teleportContainer.querySelector('.foo')!)
  311. expect(fn1).toHaveBeenCalled()
  312. triggerEvent('click', teleportContainer.querySelector('.foo2')!)
  313. expect(fn2).toHaveBeenCalled()
  314. msg.value = 'bar'
  315. await nextTick()
  316. expect(teleportContainer.innerHTML).toMatchInlineSnapshot(
  317. `"<span>bar</span><span class="bar"></span><!--teleport anchor--><span>bar2</span><span class="bar2"></span><!--teleport anchor-->"`,
  318. )
  319. })
  320. test('Teleport (disabled)', async () => {
  321. const msg = ref('foo')
  322. const fn1 = vi.fn()
  323. const fn2 = vi.fn()
  324. const Comp = () => [
  325. h('div', 'foo'),
  326. h(Teleport, { to: '#teleport3', disabled: true }, [
  327. h('span', msg.value),
  328. h('span', { class: msg.value, onClick: fn1 }),
  329. ]),
  330. h('div', { class: msg.value + '2', onClick: fn2 }, 'bar'),
  331. ]
  332. const teleportContainer = document.createElement('div')
  333. teleportContainer.id = 'teleport3'
  334. const ctx: SSRContext = {}
  335. const mainHtml = await renderToString(h(Comp), ctx)
  336. expect(mainHtml).toMatchInlineSnapshot(
  337. `"<!--[--><div>foo</div><!--teleport start--><span>foo</span><span class="foo"></span><!--teleport end--><div class="foo2">bar</div><!--]-->"`,
  338. )
  339. const teleportHtml = ctx.teleports!['#teleport3']
  340. expect(teleportHtml).toMatchInlineSnapshot(`"<!--teleport anchor-->"`)
  341. teleportContainer.innerHTML = teleportHtml
  342. document.body.appendChild(teleportContainer)
  343. const { vnode, container } = mountWithHydration(mainHtml, Comp)
  344. expect(vnode.el).toBe(container.firstChild)
  345. const children = vnode.children as VNode[]
  346. expect(children[0].el).toBe(container.childNodes[1])
  347. const teleportVnode = children[1]
  348. expect(teleportVnode.el).toBe(container.childNodes[2])
  349. expect((teleportVnode.children as VNode[])[0].el).toBe(
  350. container.childNodes[3],
  351. )
  352. expect((teleportVnode.children as VNode[])[1].el).toBe(
  353. container.childNodes[4],
  354. )
  355. expect(teleportVnode.anchor).toBe(container.childNodes[5])
  356. expect(children[2].el).toBe(container.childNodes[6])
  357. expect(teleportVnode.target).toBe(teleportContainer)
  358. expect(teleportVnode.targetAnchor).toBe(teleportContainer.childNodes[0])
  359. // // event handler
  360. triggerEvent('click', container.querySelector('.foo')!)
  361. expect(fn1).toHaveBeenCalled()
  362. triggerEvent('click', container.querySelector('.foo2')!)
  363. expect(fn2).toHaveBeenCalled()
  364. msg.value = 'bar'
  365. await nextTick()
  366. expect(container.innerHTML).toMatchInlineSnapshot(
  367. `"<!--[--><div>foo</div><!--teleport start--><span>bar</span><span class="bar"></span><!--teleport end--><div class="bar2">bar</div><!--]-->"`,
  368. )
  369. })
  370. // #6152
  371. test('Teleport (disabled + as component root)', () => {
  372. const { container } = mountWithHydration(
  373. '<!--[--><div>Parent fragment</div><!--teleport start--><div>Teleport content</div><!--teleport end--><!--]-->',
  374. () => [
  375. h('div', 'Parent fragment'),
  376. h(() =>
  377. h(Teleport, { to: 'body', disabled: true }, [
  378. h('div', 'Teleport content'),
  379. ]),
  380. ),
  381. ],
  382. )
  383. expect(document.body.innerHTML).toBe('')
  384. expect(container.innerHTML).toBe(
  385. '<!--[--><div>Parent fragment</div><!--teleport start--><div>Teleport content</div><!--teleport end--><!--]-->',
  386. )
  387. expect(
  388. `Hydration completed but contains mismatches.`,
  389. ).not.toHaveBeenWarned()
  390. })
  391. test('Teleport (as component root)', () => {
  392. const teleportContainer = document.createElement('div')
  393. teleportContainer.id = 'teleport4'
  394. teleportContainer.innerHTML = `hello<!--teleport anchor-->`
  395. document.body.appendChild(teleportContainer)
  396. const wrapper = {
  397. render() {
  398. return h(Teleport, { to: '#teleport4' }, ['hello'])
  399. },
  400. }
  401. const { vnode, container } = mountWithHydration(
  402. '<div><!--teleport start--><!--teleport end--><div></div></div>',
  403. () => h('div', [h(wrapper), h('div')]),
  404. )
  405. expect(vnode.el).toBe(container.firstChild)
  406. // component el
  407. const wrapperVNode = (vnode as any).children[0]
  408. const tpStart = container.firstChild?.firstChild
  409. const tpEnd = tpStart?.nextSibling
  410. expect(wrapperVNode.el).toBe(tpStart)
  411. expect(wrapperVNode.component.subTree.el).toBe(tpStart)
  412. expect(wrapperVNode.component.subTree.anchor).toBe(tpEnd)
  413. // next node hydrate properly
  414. const nextVNode = (vnode as any).children[1]
  415. expect(nextVNode.el).toBe(container.firstChild?.lastChild)
  416. })
  417. test('Teleport (nested)', () => {
  418. const teleportContainer = document.createElement('div')
  419. teleportContainer.id = 'teleport5'
  420. teleportContainer.innerHTML = `<div><!--teleport start--><!--teleport end--></div><!--teleport anchor--><div>child</div><!--teleport anchor-->`
  421. document.body.appendChild(teleportContainer)
  422. const { vnode, container } = mountWithHydration(
  423. '<!--teleport start--><!--teleport end-->',
  424. () =>
  425. h(Teleport, { to: '#teleport5' }, [
  426. h('div', [h(Teleport, { to: '#teleport5' }, [h('div', 'child')])]),
  427. ]),
  428. )
  429. expect(vnode.el).toBe(container.firstChild)
  430. expect(vnode.anchor).toBe(container.lastChild)
  431. const childDivVNode = (vnode as any).children[0]
  432. const div = teleportContainer.firstChild
  433. expect(childDivVNode.el).toBe(div)
  434. expect(vnode.targetAnchor).toBe(div?.nextSibling)
  435. const childTeleportVNode = childDivVNode.children[0]
  436. expect(childTeleportVNode.el).toBe(div?.firstChild)
  437. expect(childTeleportVNode.anchor).toBe(div?.lastChild)
  438. expect(childTeleportVNode.targetAnchor).toBe(teleportContainer.lastChild)
  439. expect(childTeleportVNode.children[0].el).toBe(
  440. teleportContainer.lastChild?.previousSibling,
  441. )
  442. })
  443. // compile SSR + client render fn from the same template & hydrate
  444. test('full compiler integration', async () => {
  445. const mounted: string[] = []
  446. const log = vi.fn()
  447. const toggle = ref(true)
  448. const Child = {
  449. data() {
  450. return {
  451. count: 0,
  452. text: 'hello',
  453. style: {
  454. color: 'red',
  455. },
  456. }
  457. },
  458. mounted() {
  459. mounted.push('child')
  460. },
  461. template: `
  462. <div>
  463. <span class="count" :style="style">{{ count }}</span>
  464. <button class="inc" @click="count++">inc</button>
  465. <button class="change" @click="style.color = 'green'" >change color</button>
  466. <button class="emit" @click="$emit('foo')">emit</button>
  467. <span class="text">{{ text }}</span>
  468. <input v-model="text">
  469. </div>
  470. `,
  471. }
  472. const App = {
  473. setup() {
  474. return { toggle }
  475. },
  476. mounted() {
  477. mounted.push('parent')
  478. },
  479. template: `
  480. <div>
  481. <span>hello</span>
  482. <template v-if="toggle">
  483. <Child @foo="log('child')"/>
  484. <template v-if="true">
  485. <button class="parent-click" @click="log('click')">click me</button>
  486. </template>
  487. </template>
  488. <span>hello</span>
  489. </div>`,
  490. components: {
  491. Child,
  492. },
  493. methods: {
  494. log,
  495. },
  496. }
  497. const container = document.createElement('div')
  498. // server render
  499. container.innerHTML = await renderToString(h(App))
  500. // hydrate
  501. createSSRApp(App).mount(container)
  502. // assert interactions
  503. // 1. parent button click
  504. triggerEvent('click', container.querySelector('.parent-click')!)
  505. expect(log).toHaveBeenCalledWith('click')
  506. // 2. child inc click + text interpolation
  507. const count = container.querySelector('.count') as HTMLElement
  508. expect(count.textContent).toBe(`0`)
  509. triggerEvent('click', container.querySelector('.inc')!)
  510. await nextTick()
  511. expect(count.textContent).toBe(`1`)
  512. // 3. child color click + style binding
  513. expect(count.style.color).toBe('red')
  514. triggerEvent('click', container.querySelector('.change')!)
  515. await nextTick()
  516. expect(count.style.color).toBe('green')
  517. // 4. child event emit
  518. triggerEvent('click', container.querySelector('.emit')!)
  519. expect(log).toHaveBeenCalledWith('child')
  520. // 5. child v-model
  521. const text = container.querySelector('.text')!
  522. const input = container.querySelector('input')!
  523. expect(text.textContent).toBe('hello')
  524. input.value = 'bye'
  525. triggerEvent('input', input)
  526. await nextTick()
  527. expect(text.textContent).toBe('bye')
  528. })
  529. test('handle click error in ssr mode', async () => {
  530. const App = {
  531. setup() {
  532. const throwError = () => {
  533. throw new Error('Sentry Error')
  534. }
  535. return { throwError }
  536. },
  537. template: `
  538. <div>
  539. <button class="parent-click" @click="throwError">click me</button>
  540. </div>`,
  541. }
  542. const container = document.createElement('div')
  543. // server render
  544. container.innerHTML = await renderToString(h(App))
  545. // hydrate
  546. const app = createSSRApp(App)
  547. const handler = (app.config.errorHandler = vi.fn())
  548. app.mount(container)
  549. // assert interactions
  550. // parent button click
  551. triggerEvent('click', container.querySelector('.parent-click')!)
  552. expect(handler).toHaveBeenCalled()
  553. })
  554. test('handle blur error in ssr mode', async () => {
  555. const App = {
  556. setup() {
  557. const throwError = () => {
  558. throw new Error('Sentry Error')
  559. }
  560. return { throwError }
  561. },
  562. template: `
  563. <div>
  564. <input class="parent-click" @blur="throwError"/>
  565. </div>`,
  566. }
  567. const container = document.createElement('div')
  568. // server render
  569. container.innerHTML = await renderToString(h(App))
  570. // hydrate
  571. const app = createSSRApp(App)
  572. const handler = (app.config.errorHandler = vi.fn())
  573. app.mount(container)
  574. // assert interactions
  575. // parent blur event
  576. triggerEvent('blur', container.querySelector('.parent-click')!)
  577. expect(handler).toHaveBeenCalled()
  578. })
  579. test('Suspense', async () => {
  580. const AsyncChild = {
  581. async setup() {
  582. const count = ref(0)
  583. return () =>
  584. h(
  585. 'span',
  586. {
  587. onClick: () => {
  588. count.value++
  589. },
  590. },
  591. count.value,
  592. )
  593. },
  594. }
  595. const { vnode, container } = mountWithHydration('<span>0</span>', () =>
  596. h(Suspense, () => h(AsyncChild)),
  597. )
  598. expect(vnode.el).toBe(container.firstChild)
  599. // wait for hydration to finish
  600. await new Promise(r => setTimeout(r))
  601. triggerEvent('click', container.querySelector('span')!)
  602. await nextTick()
  603. expect(container.innerHTML).toBe(`<span>1</span>`)
  604. })
  605. test('Suspense (full integration)', async () => {
  606. const mountedCalls: number[] = []
  607. const asyncDeps: Promise<any>[] = []
  608. const AsyncChild = defineComponent({
  609. props: ['n'],
  610. async setup(props) {
  611. const count = ref(props.n)
  612. onMounted(() => {
  613. mountedCalls.push(props.n)
  614. })
  615. const p = new Promise(r => setTimeout(r, props.n * 10))
  616. asyncDeps.push(p)
  617. await p
  618. return () =>
  619. h(
  620. 'span',
  621. {
  622. onClick: () => {
  623. count.value++
  624. },
  625. },
  626. count.value,
  627. )
  628. },
  629. })
  630. const done = vi.fn()
  631. const App = {
  632. template: `
  633. <Suspense @resolve="done">
  634. <div>
  635. <AsyncChild :n="1" />
  636. <AsyncChild :n="2" />
  637. </div>
  638. </Suspense>`,
  639. components: {
  640. AsyncChild,
  641. },
  642. methods: {
  643. done,
  644. },
  645. }
  646. const container = document.createElement('div')
  647. // server render
  648. container.innerHTML = await renderToString(h(App))
  649. expect(container.innerHTML).toMatchInlineSnapshot(
  650. `"<div><span>1</span><span>2</span></div>"`,
  651. )
  652. // reset asyncDeps from ssr
  653. asyncDeps.length = 0
  654. // hydrate
  655. createSSRApp(App).mount(container)
  656. expect(mountedCalls.length).toBe(0)
  657. expect(asyncDeps.length).toBe(2)
  658. // wait for hydration to complete
  659. await Promise.all(asyncDeps)
  660. await new Promise(r => setTimeout(r))
  661. // should flush buffered effects
  662. expect(mountedCalls).toMatchObject([1, 2])
  663. expect(container.innerHTML).toMatch(
  664. `<div><span>1</span><span>2</span></div>`,
  665. )
  666. const span1 = container.querySelector('span')!
  667. triggerEvent('click', span1)
  668. await nextTick()
  669. expect(container.innerHTML).toMatch(
  670. `<div><span>2</span><span>2</span></div>`,
  671. )
  672. const span2 = span1.nextSibling as Element
  673. triggerEvent('click', span2)
  674. await nextTick()
  675. expect(container.innerHTML).toMatch(
  676. `<div><span>2</span><span>3</span></div>`,
  677. )
  678. })
  679. test('async component', async () => {
  680. const spy = vi.fn()
  681. const Comp = () =>
  682. h(
  683. 'button',
  684. {
  685. onClick: spy,
  686. },
  687. 'hello!',
  688. )
  689. let serverResolve: any
  690. let AsyncComp = defineAsyncComponent(
  691. () =>
  692. new Promise(r => {
  693. serverResolve = r
  694. }),
  695. )
  696. const App = {
  697. render() {
  698. return ['hello', h(AsyncComp), 'world']
  699. },
  700. }
  701. // server render
  702. const htmlPromise = renderToString(h(App))
  703. serverResolve(Comp)
  704. const html = await htmlPromise
  705. expect(html).toMatchInlineSnapshot(
  706. `"<!--[-->hello<button>hello!</button>world<!--]-->"`,
  707. )
  708. // hydration
  709. let clientResolve: any
  710. AsyncComp = defineAsyncComponent(
  711. () =>
  712. new Promise(r => {
  713. clientResolve = r
  714. }),
  715. )
  716. const container = document.createElement('div')
  717. container.innerHTML = html
  718. createSSRApp(App).mount(container)
  719. // hydration not complete yet
  720. triggerEvent('click', container.querySelector('button')!)
  721. expect(spy).not.toHaveBeenCalled()
  722. // resolve
  723. clientResolve(Comp)
  724. await new Promise(r => setTimeout(r))
  725. // should be hydrated now
  726. triggerEvent('click', container.querySelector('button')!)
  727. expect(spy).toHaveBeenCalled()
  728. })
  729. test('update async wrapper before resolve', async () => {
  730. const Comp = {
  731. render() {
  732. return h('h1', 'Async component')
  733. },
  734. }
  735. let serverResolve: any
  736. let AsyncComp = defineAsyncComponent(
  737. () =>
  738. new Promise(r => {
  739. serverResolve = r
  740. }),
  741. )
  742. const toggle = ref(true)
  743. const App = {
  744. setup() {
  745. onMounted(() => {
  746. // change state, this makes updateComponent(AsyncComp) execute before
  747. // the async component is resolved
  748. toggle.value = false
  749. })
  750. return () => {
  751. return [toggle.value ? 'hello' : 'world', h(AsyncComp)]
  752. }
  753. },
  754. }
  755. // server render
  756. const htmlPromise = renderToString(h(App))
  757. serverResolve(Comp)
  758. const html = await htmlPromise
  759. expect(html).toMatchInlineSnapshot(
  760. `"<!--[-->hello<h1>Async component</h1><!--]-->"`,
  761. )
  762. // hydration
  763. let clientResolve: any
  764. AsyncComp = defineAsyncComponent(
  765. () =>
  766. new Promise(r => {
  767. clientResolve = r
  768. }),
  769. )
  770. const container = document.createElement('div')
  771. container.innerHTML = html
  772. createSSRApp(App).mount(container)
  773. // resolve
  774. clientResolve(Comp)
  775. await new Promise(r => setTimeout(r))
  776. // should be hydrated now
  777. expect(`Hydration node mismatch`).not.toHaveBeenWarned()
  778. expect(container.innerHTML).toMatchInlineSnapshot(
  779. `"<!--[-->world<h1>Async component</h1><!--]-->"`,
  780. )
  781. })
  782. test('hydrate safely when property used by async setup changed before render', async () => {
  783. const toggle = ref(true)
  784. const AsyncComp = {
  785. async setup() {
  786. await new Promise<void>(r => setTimeout(r, 10))
  787. return () => h('h1', 'Async component')
  788. },
  789. }
  790. const AsyncWrapper = {
  791. render() {
  792. return h(AsyncComp)
  793. },
  794. }
  795. const SiblingComp = {
  796. setup() {
  797. toggle.value = false
  798. return () => h('span')
  799. },
  800. }
  801. const App = {
  802. setup() {
  803. return () =>
  804. h(
  805. Suspense,
  806. {},
  807. {
  808. default: () => [
  809. h('main', {}, [
  810. h(AsyncWrapper, {
  811. prop: toggle.value ? 'hello' : 'world',
  812. }),
  813. h(SiblingComp),
  814. ]),
  815. ],
  816. },
  817. )
  818. },
  819. }
  820. // server render
  821. const html = await renderToString(h(App))
  822. expect(html).toMatchInlineSnapshot(
  823. `"<main><h1 prop="hello">Async component</h1><span></span></main>"`,
  824. )
  825. expect(toggle.value).toBe(false)
  826. // hydration
  827. // reset the value
  828. toggle.value = true
  829. expect(toggle.value).toBe(true)
  830. const container = document.createElement('div')
  831. container.innerHTML = html
  832. createSSRApp(App).mount(container)
  833. await new Promise(r => setTimeout(r, 10))
  834. expect(toggle.value).toBe(false)
  835. // should be hydrated now
  836. expect(container.innerHTML).toMatchInlineSnapshot(
  837. `"<main><h1 prop="world">Async component</h1><span></span></main>"`,
  838. )
  839. })
  840. test('hydrate safely when property used by deep nested async setup changed before render', async () => {
  841. const toggle = ref(true)
  842. const AsyncComp = {
  843. async setup() {
  844. await new Promise<void>(r => setTimeout(r, 10))
  845. return () => h('h1', 'Async component')
  846. },
  847. }
  848. const AsyncWrapper = { render: () => h(AsyncComp) }
  849. const AsyncWrapperWrapper = { render: () => h(AsyncWrapper) }
  850. const SiblingComp = {
  851. setup() {
  852. toggle.value = false
  853. return () => h('span')
  854. },
  855. }
  856. const App = {
  857. setup() {
  858. return () =>
  859. h(
  860. Suspense,
  861. {},
  862. {
  863. default: () => [
  864. h('main', {}, [
  865. h(AsyncWrapperWrapper, {
  866. prop: toggle.value ? 'hello' : 'world',
  867. }),
  868. h(SiblingComp),
  869. ]),
  870. ],
  871. },
  872. )
  873. },
  874. }
  875. // server render
  876. const html = await renderToString(h(App))
  877. expect(html).toMatchInlineSnapshot(
  878. `"<main><h1 prop="hello">Async component</h1><span></span></main>"`,
  879. )
  880. expect(toggle.value).toBe(false)
  881. // hydration
  882. // reset the value
  883. toggle.value = true
  884. expect(toggle.value).toBe(true)
  885. const container = document.createElement('div')
  886. container.innerHTML = html
  887. createSSRApp(App).mount(container)
  888. await new Promise(r => setTimeout(r, 10))
  889. expect(toggle.value).toBe(false)
  890. // should be hydrated now
  891. expect(container.innerHTML).toMatchInlineSnapshot(
  892. `"<main><h1 prop="world">Async component</h1><span></span></main>"`,
  893. )
  894. })
  895. // #3787
  896. test('unmount async wrapper before load', async () => {
  897. let resolve: any
  898. const AsyncComp = defineAsyncComponent(
  899. () =>
  900. new Promise(r => {
  901. resolve = r
  902. }),
  903. )
  904. const show = ref(true)
  905. const root = document.createElement('div')
  906. root.innerHTML = '<div><div>async</div></div>'
  907. createSSRApp({
  908. render() {
  909. return h('div', [show.value ? h(AsyncComp) : h('div', 'hi')])
  910. },
  911. }).mount(root)
  912. show.value = false
  913. await nextTick()
  914. expect(root.innerHTML).toBe('<div><div>hi</div></div>')
  915. resolve({})
  916. })
  917. test('unmount async wrapper before load (fragment)', async () => {
  918. let resolve: any
  919. const AsyncComp = defineAsyncComponent(
  920. () =>
  921. new Promise(r => {
  922. resolve = r
  923. }),
  924. )
  925. const show = ref(true)
  926. const root = document.createElement('div')
  927. root.innerHTML = '<div><!--[-->async<!--]--></div>'
  928. createSSRApp({
  929. render() {
  930. return h('div', [show.value ? h(AsyncComp) : h('div', 'hi')])
  931. },
  932. }).mount(root)
  933. show.value = false
  934. await nextTick()
  935. expect(root.innerHTML).toBe('<div><div>hi</div></div>')
  936. resolve({})
  937. })
  938. test('elements with camel-case in svg ', () => {
  939. const { vnode, container } = mountWithHydration(
  940. '<animateTransform></animateTransform>',
  941. () => h('animateTransform'),
  942. )
  943. expect(vnode.el).toBe(container.firstChild)
  944. expect(`Hydration node mismatch`).not.toHaveBeenWarned()
  945. })
  946. test('SVG as a mount container', () => {
  947. const svgContainer = document.createElement('svg')
  948. svgContainer.innerHTML = '<g></g>'
  949. const app = createSSRApp({
  950. render: () => h('g'),
  951. })
  952. expect(
  953. (
  954. app.mount(svgContainer).$.subTree as VNode<Node, Element> & {
  955. el: Element
  956. }
  957. ).el instanceof SVGElement,
  958. )
  959. })
  960. test('force hydrate prop with `.prop` modifier', () => {
  961. const { container } = mountWithHydration('<input type="checkbox">', () =>
  962. h('input', {
  963. type: 'checkbox',
  964. '.indeterminate': true,
  965. }),
  966. )
  967. expect((container.firstChild! as any).indeterminate).toBe(true)
  968. })
  969. test('force hydrate input v-model with non-string value bindings', () => {
  970. const { container } = mountWithHydration(
  971. '<input type="checkbox" value="true">',
  972. () =>
  973. withDirectives(
  974. createVNode(
  975. 'input',
  976. { type: 'checkbox', 'true-value': true },
  977. null,
  978. PatchFlags.PROPS,
  979. ['true-value'],
  980. ),
  981. [[vModelCheckbox, true]],
  982. ),
  983. )
  984. expect((container.firstChild as any)._trueValue).toBe(true)
  985. })
  986. test('force hydrate checkbox with indeterminate', () => {
  987. const { container } = mountWithHydration(
  988. '<input type="checkbox" indeterminate>',
  989. () =>
  990. createVNode(
  991. 'input',
  992. { type: 'checkbox', indeterminate: '' },
  993. null,
  994. PatchFlags.HOISTED,
  995. ),
  996. )
  997. expect((container.firstChild as any).indeterminate).toBe(true)
  998. })
  999. test('force hydrate select option with non-string value bindings', () => {
  1000. const { container } = mountWithHydration(
  1001. '<select><option value="true">ok</option></select>',
  1002. () =>
  1003. h('select', [
  1004. // hoisted because bound value is a constant...
  1005. createVNode('option', { value: true }, null, -1 /* HOISTED */),
  1006. ]),
  1007. )
  1008. expect((container.firstChild!.firstChild as any)._value).toBe(true)
  1009. })
  1010. // #5728
  1011. test('empty text node in slot', () => {
  1012. const Comp = {
  1013. render(this: any) {
  1014. return renderSlot(this.$slots, 'default', {}, () => [
  1015. createTextVNode(''),
  1016. ])
  1017. },
  1018. }
  1019. const { container, vnode } = mountWithHydration('<!--[--><!--]-->', () =>
  1020. h(Comp),
  1021. )
  1022. expect(container.childNodes.length).toBe(3)
  1023. const text = container.childNodes[1]
  1024. expect(text.nodeType).toBe(3)
  1025. expect(vnode.el).toBe(container.childNodes[0])
  1026. // component => slot fragment => text node
  1027. expect((vnode as any).component?.subTree.children[0].el).toBe(text)
  1028. })
  1029. // #7215
  1030. test('empty text node', () => {
  1031. const Comp = {
  1032. render(this: any) {
  1033. return h('p', [''])
  1034. },
  1035. }
  1036. const { container } = mountWithHydration('<p></p>', () => h(Comp))
  1037. expect(container.childNodes.length).toBe(1)
  1038. const p = container.childNodes[0]
  1039. expect(p.childNodes.length).toBe(1)
  1040. const text = p.childNodes[0]
  1041. expect(text.nodeType).toBe(3)
  1042. })
  1043. // #11372
  1044. test('object style value tracking in prod', async () => {
  1045. __DEV__ = false
  1046. try {
  1047. const style = reactive({ color: 'red' })
  1048. const Comp = {
  1049. render(this: any) {
  1050. return (
  1051. openBlock(),
  1052. createElementBlock(
  1053. 'div',
  1054. {
  1055. style: normalizeStyle(style),
  1056. },
  1057. null,
  1058. 4 /* STYLE */,
  1059. )
  1060. )
  1061. },
  1062. }
  1063. const { container } = mountWithHydration(
  1064. `<div style="color: red;"></div>`,
  1065. () => h(Comp),
  1066. )
  1067. style.color = 'green'
  1068. await nextTick()
  1069. expect(container.innerHTML).toBe(`<div style="color: green;"></div>`)
  1070. } finally {
  1071. __DEV__ = true
  1072. }
  1073. })
  1074. test('app.unmount()', async () => {
  1075. const container = document.createElement('DIV')
  1076. container.innerHTML = '<button></button>'
  1077. const App = defineComponent({
  1078. setup(_, { expose }) {
  1079. const count = ref(0)
  1080. expose({ count })
  1081. return () =>
  1082. h('button', {
  1083. onClick: () => count.value++,
  1084. })
  1085. },
  1086. })
  1087. const app = createSSRApp(App)
  1088. const vm = app.mount(container)
  1089. await nextTick()
  1090. expect((container as any)._vnode).toBeDefined()
  1091. // @ts-expect-error - expose()'d properties are not available on vm type
  1092. expect(vm.count).toBe(0)
  1093. app.unmount()
  1094. expect((container as any)._vnode).toBe(null)
  1095. })
  1096. // #6637
  1097. test('stringified root fragment', () => {
  1098. mountWithHydration(`<!--[--><div></div><!--]-->`, () =>
  1099. createStaticVNode(`<div></div>`, 1),
  1100. )
  1101. expect(`mismatch`).not.toHaveBeenWarned()
  1102. })
  1103. test('transition appear', () => {
  1104. const { vnode, container } = mountWithHydration(
  1105. `<template><div>foo</div></template>`,
  1106. () =>
  1107. h(
  1108. Transition,
  1109. { appear: true },
  1110. {
  1111. default: () => h('div', 'foo'),
  1112. },
  1113. ),
  1114. )
  1115. expect(container.firstChild).toMatchInlineSnapshot(`
  1116. <div
  1117. class="v-enter-from v-enter-active"
  1118. >
  1119. foo
  1120. </div>
  1121. `)
  1122. expect(vnode.el).toBe(container.firstChild)
  1123. expect(`mismatch`).not.toHaveBeenWarned()
  1124. })
  1125. test('transition appear with v-if', () => {
  1126. const show = false
  1127. const { vnode, container } = mountWithHydration(
  1128. `<template><!----></template>`,
  1129. () =>
  1130. h(
  1131. Transition,
  1132. { appear: true },
  1133. {
  1134. default: () => (show ? h('div', 'foo') : createCommentVNode('')),
  1135. },
  1136. ),
  1137. )
  1138. expect(container.firstChild).toMatchInlineSnapshot('<!---->')
  1139. expect(vnode.el).toBe(container.firstChild)
  1140. expect(`mismatch`).not.toHaveBeenWarned()
  1141. })
  1142. test('transition appear with v-show', () => {
  1143. const show = false
  1144. const { vnode, container } = mountWithHydration(
  1145. `<template><div style="display: none;">foo</div></template>`,
  1146. () =>
  1147. h(
  1148. Transition,
  1149. { appear: true },
  1150. {
  1151. default: () =>
  1152. withDirectives(createVNode('div', null, 'foo'), [[vShow, show]]),
  1153. },
  1154. ),
  1155. )
  1156. expect(container.firstChild).toMatchInlineSnapshot(`
  1157. <div
  1158. class="v-enter-from v-enter-active"
  1159. style="display: none;"
  1160. >
  1161. foo
  1162. </div>
  1163. `)
  1164. expect((container.firstChild as any)[vShowOriginalDisplay]).toBe('')
  1165. expect(vnode.el).toBe(container.firstChild)
  1166. expect(`mismatch`).not.toHaveBeenWarned()
  1167. })
  1168. test('transition appear w/ event listener', async () => {
  1169. const container = document.createElement('div')
  1170. container.innerHTML = `<template><button>0</button></template>`
  1171. createSSRApp({
  1172. data() {
  1173. return {
  1174. count: 0,
  1175. }
  1176. },
  1177. template: `
  1178. <Transition appear>
  1179. <button @click="count++">{{count}}</button>
  1180. </Transition>
  1181. `,
  1182. }).mount(container)
  1183. expect(container.firstChild).toMatchInlineSnapshot(`
  1184. <button
  1185. class="v-enter-from v-enter-active"
  1186. >
  1187. 0
  1188. </button>
  1189. `)
  1190. triggerEvent('click', container.querySelector('button')!)
  1191. await nextTick()
  1192. expect(container.firstChild).toMatchInlineSnapshot(`
  1193. <button
  1194. class="v-enter-from v-enter-active"
  1195. >
  1196. 1
  1197. </button>
  1198. `)
  1199. })
  1200. // #10607
  1201. test('update component stable slot (prod + optimized mode)', async () => {
  1202. __DEV__ = false
  1203. try {
  1204. const container = document.createElement('div')
  1205. container.innerHTML = `<template><div show="false"><!--[--><div><div><!----></div></div><div>0</div><!--]--></div></template>`
  1206. const Comp = {
  1207. render(this: any) {
  1208. return (
  1209. openBlock(),
  1210. createElementBlock('div', null, [
  1211. renderSlot(this.$slots, 'default'),
  1212. ])
  1213. )
  1214. },
  1215. }
  1216. const show = ref(false)
  1217. const clicked = ref(false)
  1218. const Wrapper = {
  1219. setup() {
  1220. const items = ref<number[]>([])
  1221. onMounted(() => {
  1222. items.value = [1]
  1223. })
  1224. return () => {
  1225. return (
  1226. openBlock(),
  1227. createBlock(Comp, null, {
  1228. default: withCtx(() => [
  1229. createElementVNode('div', null, [
  1230. createElementVNode('div', null, [
  1231. clicked.value
  1232. ? (openBlock(),
  1233. createElementBlock('div', { key: 0 }, 'foo'))
  1234. : createCommentVNode('v-if', true),
  1235. ]),
  1236. ]),
  1237. createElementVNode(
  1238. 'div',
  1239. null,
  1240. items.value.length,
  1241. 1 /* TEXT */,
  1242. ),
  1243. ]),
  1244. _: 1 /* STABLE */,
  1245. })
  1246. )
  1247. }
  1248. },
  1249. }
  1250. createSSRApp({
  1251. components: { Wrapper },
  1252. data() {
  1253. return { show }
  1254. },
  1255. template: `<Wrapper :show="show"/>`,
  1256. }).mount(container)
  1257. await nextTick()
  1258. expect(container.innerHTML).toBe(
  1259. `<div show="false"><!--[--><div><div><!----></div></div><div>1</div><!--]--></div>`,
  1260. )
  1261. show.value = true
  1262. await nextTick()
  1263. expect(async () => {
  1264. clicked.value = true
  1265. await nextTick()
  1266. }).not.toThrow("Cannot read properties of null (reading 'insertBefore')")
  1267. await nextTick()
  1268. expect(container.innerHTML).toBe(
  1269. `<div show="true"><!--[--><div><div><div>foo</div></div></div><div>1</div><!--]--></div>`,
  1270. )
  1271. } catch (e) {
  1272. throw e
  1273. } finally {
  1274. __DEV__ = true
  1275. }
  1276. })
  1277. describe('mismatch handling', () => {
  1278. test('text node', () => {
  1279. const { container } = mountWithHydration(`foo`, () => 'bar')
  1280. expect(container.textContent).toBe('bar')
  1281. expect(`Hydration text mismatch`).toHaveBeenWarned()
  1282. })
  1283. test('element text content', () => {
  1284. const { container } = mountWithHydration(`<div>foo</div>`, () =>
  1285. h('div', 'bar'),
  1286. )
  1287. expect(container.innerHTML).toBe('<div>bar</div>')
  1288. expect(`Hydration text content mismatch`).toHaveBeenWarned()
  1289. })
  1290. test('not enough children', () => {
  1291. const { container } = mountWithHydration(`<div></div>`, () =>
  1292. h('div', [h('span', 'foo'), h('span', 'bar')]),
  1293. )
  1294. expect(container.innerHTML).toBe(
  1295. '<div><span>foo</span><span>bar</span></div>',
  1296. )
  1297. expect(`Hydration children mismatch`).toHaveBeenWarned()
  1298. })
  1299. test('too many children', () => {
  1300. const { container } = mountWithHydration(
  1301. `<div><span>foo</span><span>bar</span></div>`,
  1302. () => h('div', [h('span', 'foo')]),
  1303. )
  1304. expect(container.innerHTML).toBe('<div><span>foo</span></div>')
  1305. expect(`Hydration children mismatch`).toHaveBeenWarned()
  1306. })
  1307. test('complete mismatch', () => {
  1308. const { container } = mountWithHydration(
  1309. `<div><span>foo</span><span>bar</span></div>`,
  1310. () => h('div', [h('div', 'foo'), h('p', 'bar')]),
  1311. )
  1312. expect(container.innerHTML).toBe('<div><div>foo</div><p>bar</p></div>')
  1313. expect(`Hydration node mismatch`).toHaveBeenWarnedTimes(2)
  1314. })
  1315. test('fragment mismatch removal', () => {
  1316. const { container } = mountWithHydration(
  1317. `<div><!--[--><div>foo</div><div>bar</div><!--]--></div>`,
  1318. () => h('div', [h('span', 'replaced')]),
  1319. )
  1320. expect(container.innerHTML).toBe('<div><span>replaced</span></div>')
  1321. expect(`Hydration node mismatch`).toHaveBeenWarned()
  1322. })
  1323. test('fragment not enough children', () => {
  1324. const { container } = mountWithHydration(
  1325. `<div><!--[--><div>foo</div><!--]--><div>baz</div></div>`,
  1326. () => h('div', [[h('div', 'foo'), h('div', 'bar')], h('div', 'baz')]),
  1327. )
  1328. expect(container.innerHTML).toBe(
  1329. '<div><!--[--><div>foo</div><div>bar</div><!--]--><div>baz</div></div>',
  1330. )
  1331. expect(`Hydration node mismatch`).toHaveBeenWarned()
  1332. })
  1333. test('fragment too many children', () => {
  1334. const { container } = mountWithHydration(
  1335. `<div><!--[--><div>foo</div><div>bar</div><!--]--><div>baz</div></div>`,
  1336. () => h('div', [[h('div', 'foo')], h('div', 'baz')]),
  1337. )
  1338. expect(container.innerHTML).toBe(
  1339. '<div><!--[--><div>foo</div><!--]--><div>baz</div></div>',
  1340. )
  1341. // fragment ends early and attempts to hydrate the extra <div>bar</div>
  1342. // as 2nd fragment child.
  1343. expect(`Hydration text content mismatch`).toHaveBeenWarned()
  1344. // excessive children removal
  1345. expect(`Hydration children mismatch`).toHaveBeenWarned()
  1346. })
  1347. test('Teleport target has empty children', () => {
  1348. const teleportContainer = document.createElement('div')
  1349. teleportContainer.id = 'teleport'
  1350. document.body.appendChild(teleportContainer)
  1351. mountWithHydration('<!--teleport start--><!--teleport end-->', () =>
  1352. h(Teleport, { to: '#teleport' }, [h('span', 'value')]),
  1353. )
  1354. expect(teleportContainer.innerHTML).toBe(`<span>value</span>`)
  1355. expect(`Hydration children mismatch`).toHaveBeenWarned()
  1356. })
  1357. test('comment mismatch (element)', () => {
  1358. const { container } = mountWithHydration(`<div><span></span></div>`, () =>
  1359. h('div', [createCommentVNode('hi')]),
  1360. )
  1361. expect(container.innerHTML).toBe('<div><!--hi--></div>')
  1362. expect(`Hydration node mismatch`).toHaveBeenWarned()
  1363. })
  1364. test('comment mismatch (text)', () => {
  1365. const { container } = mountWithHydration(`<div>foobar</div>`, () =>
  1366. h('div', [createCommentVNode('hi')]),
  1367. )
  1368. expect(container.innerHTML).toBe('<div><!--hi--></div>')
  1369. expect(`Hydration node mismatch`).toHaveBeenWarned()
  1370. })
  1371. test('class mismatch', () => {
  1372. mountWithHydration(`<div class="foo bar"></div>`, () =>
  1373. h('div', { class: ['foo', 'bar'] }),
  1374. )
  1375. mountWithHydration(`<div class="foo bar"></div>`, () =>
  1376. h('div', { class: { foo: true, bar: true } }),
  1377. )
  1378. mountWithHydration(`<div class="foo bar"></div>`, () =>
  1379. h('div', { class: 'foo bar' }),
  1380. )
  1381. // SVG classes
  1382. mountWithHydration(`<svg class="foo bar"></svg>`, () =>
  1383. h('svg', { class: 'foo bar' }),
  1384. )
  1385. // class with different order
  1386. mountWithHydration(`<div class="foo bar"></div>`, () =>
  1387. h('div', { class: 'bar foo' }),
  1388. )
  1389. expect(`Hydration class mismatch`).not.toHaveBeenWarned()
  1390. mountWithHydration(`<div class="foo bar"></div>`, () =>
  1391. h('div', { class: 'foo' }),
  1392. )
  1393. expect(`Hydration class mismatch`).toHaveBeenWarned()
  1394. })
  1395. test('style mismatch', () => {
  1396. mountWithHydration(`<div style="color:red;"></div>`, () =>
  1397. h('div', { style: { color: 'red' } }),
  1398. )
  1399. mountWithHydration(`<div style="color:red;"></div>`, () =>
  1400. h('div', { style: `color:red;` }),
  1401. )
  1402. mountWithHydration(
  1403. `<div style="color:red; font-size: 12px;"></div>`,
  1404. () => h('div', { style: `font-size: 12px; color:red;` }),
  1405. )
  1406. mountWithHydration(`<div style="color:red;display:none;"></div>`, () =>
  1407. withDirectives(createVNode('div', { style: 'color: red' }, ''), [
  1408. [vShow, false],
  1409. ]),
  1410. )
  1411. expect(`Hydration style mismatch`).not.toHaveBeenWarned()
  1412. mountWithHydration(`<div style="color:red;"></div>`, () =>
  1413. h('div', { style: { color: 'green' } }),
  1414. )
  1415. expect(`Hydration style mismatch`).toHaveBeenWarnedTimes(1)
  1416. })
  1417. test('style mismatch when no style attribute is present', () => {
  1418. mountWithHydration(`<div></div>`, () =>
  1419. h('div', { style: { color: 'red' } }),
  1420. )
  1421. expect(`Hydration style mismatch`).toHaveBeenWarnedTimes(1)
  1422. })
  1423. test('style mismatch w/ v-show', () => {
  1424. mountWithHydration(`<div style="color:red;display:none"></div>`, () =>
  1425. withDirectives(createVNode('div', { style: 'color: red' }, ''), [
  1426. [vShow, false],
  1427. ]),
  1428. )
  1429. expect(`Hydration style mismatch`).not.toHaveBeenWarned()
  1430. mountWithHydration(`<div style="color:red;"></div>`, () =>
  1431. withDirectives(createVNode('div', { style: 'color: red' }, ''), [
  1432. [vShow, false],
  1433. ]),
  1434. )
  1435. expect(`Hydration style mismatch`).toHaveBeenWarnedTimes(1)
  1436. })
  1437. test('attr mismatch', () => {
  1438. mountWithHydration(`<div id="foo"></div>`, () => h('div', { id: 'foo' }))
  1439. mountWithHydration(`<div spellcheck></div>`, () =>
  1440. h('div', { spellcheck: '' }),
  1441. )
  1442. mountWithHydration(`<div></div>`, () => h('div', { id: undefined }))
  1443. // boolean
  1444. mountWithHydration(`<select multiple></div>`, () =>
  1445. h('select', { multiple: true }),
  1446. )
  1447. mountWithHydration(`<select multiple></div>`, () =>
  1448. h('select', { multiple: 'multiple' }),
  1449. )
  1450. expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
  1451. mountWithHydration(`<div></div>`, () => h('div', { id: 'foo' }))
  1452. expect(`Hydration attribute mismatch`).toHaveBeenWarnedTimes(1)
  1453. mountWithHydration(`<div id="bar"></div>`, () => h('div', { id: 'foo' }))
  1454. expect(`Hydration attribute mismatch`).toHaveBeenWarnedTimes(2)
  1455. })
  1456. test('attr special case: textarea value', () => {
  1457. mountWithHydration(`<textarea>foo</textarea>`, () =>
  1458. h('textarea', { value: 'foo' }),
  1459. )
  1460. mountWithHydration(`<textarea></textarea>`, () =>
  1461. h('textarea', { value: '' }),
  1462. )
  1463. expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
  1464. mountWithHydration(`<textarea>foo</textarea>`, () =>
  1465. h('textarea', { value: 'bar' }),
  1466. )
  1467. expect(`Hydration attribute mismatch`).toHaveBeenWarned()
  1468. })
  1469. test('boolean attr handling', () => {
  1470. mountWithHydration(`<input />`, () => h('input', { readonly: false }))
  1471. expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
  1472. mountWithHydration(`<input readonly />`, () =>
  1473. h('input', { readonly: true }),
  1474. )
  1475. expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
  1476. mountWithHydration(`<input readonly="readonly" />`, () =>
  1477. h('input', { readonly: true }),
  1478. )
  1479. expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
  1480. })
  1481. test('client value is null or undefined', () => {
  1482. mountWithHydration(`<div></div>`, () =>
  1483. h('div', { draggable: undefined }),
  1484. )
  1485. expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
  1486. mountWithHydration(`<input />`, () => h('input', { type: null }))
  1487. expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
  1488. })
  1489. test('should not warn against object values', () => {
  1490. mountWithHydration(`<input />`, () => h('input', { from: {} }))
  1491. expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
  1492. })
  1493. test('should not warn on falsy bindings of non-property keys', () => {
  1494. mountWithHydration(`<button />`, () => h('button', { href: undefined }))
  1495. expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
  1496. })
  1497. test('should not warn on non-renderable option values', () => {
  1498. mountWithHydration(`<select><option>hello</option></select>`, () =>
  1499. h('select', [h('option', { value: ['foo'] }, 'hello')]),
  1500. )
  1501. expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
  1502. })
  1503. test('should not warn css v-bind', () => {
  1504. const container = document.createElement('div')
  1505. container.innerHTML = `<div style="--foo:red;color:var(--foo);" />`
  1506. const app = createSSRApp({
  1507. setup() {
  1508. useCssVars(() => ({
  1509. foo: 'red',
  1510. }))
  1511. return () => h('div', { style: { color: 'var(--foo)' } })
  1512. },
  1513. })
  1514. app.mount(container)
  1515. expect(`Hydration style mismatch`).not.toHaveBeenWarned()
  1516. })
  1517. // #10317 - test case from #10325
  1518. test('css vars should only be added to expected on component root dom', () => {
  1519. const container = document.createElement('div')
  1520. container.innerHTML = `<div style="--foo:red;"><div style="color:var(--foo);" /></div>`
  1521. const app = createSSRApp({
  1522. setup() {
  1523. useCssVars(() => ({
  1524. foo: 'red',
  1525. }))
  1526. return () =>
  1527. h('div', null, [h('div', { style: { color: 'var(--foo)' } })])
  1528. },
  1529. })
  1530. app.mount(container)
  1531. expect(`Hydration style mismatch`).not.toHaveBeenWarned()
  1532. })
  1533. // #11188
  1534. test('css vars support fallthrough', () => {
  1535. const container = document.createElement('div')
  1536. container.innerHTML = `<div style="padding: 4px;--foo:red;"></div>`
  1537. const app = createSSRApp({
  1538. setup() {
  1539. useCssVars(() => ({
  1540. foo: 'red',
  1541. }))
  1542. return () => h(Child)
  1543. },
  1544. })
  1545. const Child = {
  1546. setup() {
  1547. return () => h('div', { style: 'padding: 4px' })
  1548. },
  1549. }
  1550. app.mount(container)
  1551. expect(`Hydration style mismatch`).not.toHaveBeenWarned()
  1552. })
  1553. // #11189
  1554. test('should not warn for directives that mutate DOM in created', () => {
  1555. const container = document.createElement('div')
  1556. container.innerHTML = `<div class="test red"></div>`
  1557. const vColor: ObjectDirective = {
  1558. created(el, binding) {
  1559. el.classList.add(binding.value)
  1560. },
  1561. }
  1562. const app = createSSRApp({
  1563. setup() {
  1564. return () =>
  1565. withDirectives(h('div', { class: 'test' }), [[vColor, 'red']])
  1566. },
  1567. })
  1568. app.mount(container)
  1569. expect(`Hydration style mismatch`).not.toHaveBeenWarned()
  1570. })
  1571. })
  1572. })