hydration.spec.ts 51 KB

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