hydration.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. import {
  2. createSSRApp,
  3. h,
  4. ref,
  5. nextTick,
  6. VNode,
  7. Portal,
  8. createStaticVNode,
  9. Suspense,
  10. onMounted,
  11. createAsyncComponent
  12. } from '@vue/runtime-dom'
  13. import { renderToString } from '@vue/server-renderer'
  14. import { mockWarn } from '@vue/shared'
  15. function mountWithHydration(html: string, render: () => any) {
  16. const container = document.createElement('div')
  17. container.innerHTML = html
  18. const app = createSSRApp({
  19. render
  20. })
  21. return {
  22. vnode: app.mount(container).$.subTree as VNode<Node, Element> & {
  23. el: Element
  24. },
  25. container
  26. }
  27. }
  28. const triggerEvent = (type: string, el: Element) => {
  29. const event = new Event(type)
  30. el.dispatchEvent(event)
  31. }
  32. describe('SSR hydration', () => {
  33. mockWarn()
  34. test('text', async () => {
  35. const msg = ref('foo')
  36. const { vnode, container } = mountWithHydration('foo', () => msg.value)
  37. expect(vnode.el).toBe(container.firstChild)
  38. expect(container.textContent).toBe('foo')
  39. msg.value = 'bar'
  40. await nextTick()
  41. expect(container.textContent).toBe('bar')
  42. })
  43. test('comment', () => {
  44. const { vnode, container } = mountWithHydration('<!---->', () => null)
  45. expect(vnode.el).toBe(container.firstChild)
  46. expect(vnode.el.nodeType).toBe(8) // comment
  47. })
  48. test('static', () => {
  49. const html = '<div><span>hello</span></div>'
  50. const { vnode, container } = mountWithHydration(html, () =>
  51. createStaticVNode(html)
  52. )
  53. expect(vnode.el).toBe(container.firstChild)
  54. expect(vnode.el.outerHTML).toBe(html)
  55. })
  56. test('element with text children', async () => {
  57. const msg = ref('foo')
  58. const { vnode, container } = mountWithHydration(
  59. '<div class="foo">foo</div>',
  60. () => h('div', { class: msg.value }, msg.value)
  61. )
  62. expect(vnode.el).toBe(container.firstChild)
  63. expect(container.firstChild!.textContent).toBe('foo')
  64. msg.value = 'bar'
  65. await nextTick()
  66. expect(container.innerHTML).toBe(`<div class="bar">bar</div>`)
  67. })
  68. test('element with elements children', async () => {
  69. const msg = ref('foo')
  70. const fn = jest.fn()
  71. const { vnode, container } = mountWithHydration(
  72. '<div><span>foo</span><span class="foo"></span></div>',
  73. () =>
  74. h('div', [
  75. h('span', msg.value),
  76. h('span', { class: msg.value, onClick: fn })
  77. ])
  78. )
  79. expect(vnode.el).toBe(container.firstChild)
  80. expect((vnode.children as VNode[])[0].el).toBe(
  81. container.firstChild!.childNodes[0]
  82. )
  83. expect((vnode.children as VNode[])[1].el).toBe(
  84. container.firstChild!.childNodes[1]
  85. )
  86. // event handler
  87. triggerEvent('click', vnode.el.querySelector('.foo')!)
  88. expect(fn).toHaveBeenCalled()
  89. msg.value = 'bar'
  90. await nextTick()
  91. expect(vnode.el.innerHTML).toBe(`<span>bar</span><span class="bar"></span>`)
  92. })
  93. test('Fragment', async () => {
  94. const msg = ref('foo')
  95. const fn = jest.fn()
  96. const { vnode, container } = mountWithHydration(
  97. '<div><!--[--><span>foo</span><!--[--><span class="foo"></span><!--]--><!--]--></div>',
  98. () =>
  99. h('div', [
  100. [h('span', msg.value), [h('span', { class: msg.value, onClick: fn })]]
  101. ])
  102. )
  103. expect(vnode.el).toBe(container.firstChild)
  104. expect(vnode.el.innerHTML).toBe(
  105. `<!--[--><span>foo</span><!--[--><span class="foo"></span><!--]--><!--]-->`
  106. )
  107. // start fragment 1
  108. const fragment1 = (vnode.children as VNode[])[0]
  109. expect(fragment1.el).toBe(vnode.el.childNodes[0])
  110. const fragment1Children = fragment1.children as VNode[]
  111. // first <span>
  112. expect(fragment1Children[0].el!.tagName).toBe('SPAN')
  113. expect(fragment1Children[0].el).toBe(vnode.el.childNodes[1])
  114. // start fragment 2
  115. const fragment2 = fragment1Children[1]
  116. expect(fragment2.el).toBe(vnode.el.childNodes[2])
  117. const fragment2Children = fragment2.children as VNode[]
  118. // second <span>
  119. expect(fragment2Children[0].el!.tagName).toBe('SPAN')
  120. expect(fragment2Children[0].el).toBe(vnode.el.childNodes[3])
  121. // end fragment 2
  122. expect(fragment2.anchor).toBe(vnode.el.childNodes[4])
  123. // end fragment 1
  124. expect(fragment1.anchor).toBe(vnode.el.childNodes[5])
  125. // event handler
  126. triggerEvent('click', vnode.el.querySelector('.foo')!)
  127. expect(fn).toHaveBeenCalled()
  128. msg.value = 'bar'
  129. await nextTick()
  130. expect(vnode.el.innerHTML).toBe(
  131. `<!--[--><span>bar</span><!--[--><span class="bar"></span><!--]--><!--]-->`
  132. )
  133. })
  134. test('Portal', async () => {
  135. const msg = ref('foo')
  136. const fn = jest.fn()
  137. const portalContainer = document.createElement('div')
  138. portalContainer.id = 'portal'
  139. portalContainer.innerHTML = `<span>foo</span><span class="foo"></span>`
  140. document.body.appendChild(portalContainer)
  141. const { vnode, container } = mountWithHydration('<!--portal-->', () =>
  142. h(Portal, { target: '#portal' }, [
  143. h('span', msg.value),
  144. h('span', { class: msg.value, onClick: fn })
  145. ])
  146. )
  147. expect(vnode.el).toBe(container.firstChild)
  148. expect((vnode.children as VNode[])[0].el).toBe(
  149. portalContainer.childNodes[0]
  150. )
  151. expect((vnode.children as VNode[])[1].el).toBe(
  152. portalContainer.childNodes[1]
  153. )
  154. // event handler
  155. triggerEvent('click', portalContainer.querySelector('.foo')!)
  156. expect(fn).toHaveBeenCalled()
  157. msg.value = 'bar'
  158. await nextTick()
  159. expect(portalContainer.innerHTML).toBe(
  160. `<span>bar</span><span class="bar"></span>`
  161. )
  162. })
  163. // compile SSR + client render fn from the same template & hydrate
  164. test('full compiler integration', async () => {
  165. const mounted: string[] = []
  166. const log = jest.fn()
  167. const toggle = ref(true)
  168. const Child = {
  169. data() {
  170. return {
  171. count: 0,
  172. text: 'hello',
  173. style: {
  174. color: 'red'
  175. }
  176. }
  177. },
  178. mounted() {
  179. mounted.push('child')
  180. },
  181. template: `
  182. <div>
  183. <span class="count" :style="style">{{ count }}</span>
  184. <button class="inc" @click="count++">inc</button>
  185. <button class="change" @click="style.color = 'green'" >change color</button>
  186. <button class="emit" @click="$emit('foo')">emit</button>
  187. <span class="text">{{ text }}</span>
  188. <input v-model="text">
  189. </div>
  190. `
  191. }
  192. const App = {
  193. setup() {
  194. return { toggle }
  195. },
  196. mounted() {
  197. mounted.push('parent')
  198. },
  199. template: `
  200. <div>
  201. <span>hello</span>
  202. <template v-if="toggle">
  203. <Child @foo="log('child')"/>
  204. <template v-if="true">
  205. <button class="parent-click" @click="log('click')">click me</button>
  206. </template>
  207. </template>
  208. <span>hello</span>
  209. </div>`,
  210. components: {
  211. Child
  212. },
  213. methods: {
  214. log
  215. }
  216. }
  217. const container = document.createElement('div')
  218. // server render
  219. container.innerHTML = await renderToString(h(App))
  220. // hydrate
  221. createSSRApp(App).mount(container)
  222. // assert interactions
  223. // 1. parent button click
  224. triggerEvent('click', container.querySelector('.parent-click')!)
  225. expect(log).toHaveBeenCalledWith('click')
  226. // 2. child inc click + text interpolation
  227. const count = container.querySelector('.count') as HTMLElement
  228. expect(count.textContent).toBe(`0`)
  229. triggerEvent('click', container.querySelector('.inc')!)
  230. await nextTick()
  231. expect(count.textContent).toBe(`1`)
  232. // 3. child color click + style binding
  233. expect(count.style.color).toBe('red')
  234. triggerEvent('click', container.querySelector('.change')!)
  235. await nextTick()
  236. expect(count.style.color).toBe('green')
  237. // 4. child event emit
  238. triggerEvent('click', container.querySelector('.emit')!)
  239. expect(log).toHaveBeenCalledWith('child')
  240. // 5. child v-model
  241. const text = container.querySelector('.text')!
  242. const input = container.querySelector('input')!
  243. expect(text.textContent).toBe('hello')
  244. input.value = 'bye'
  245. triggerEvent('input', input)
  246. await nextTick()
  247. expect(text.textContent).toBe('bye')
  248. })
  249. test('Suspense', async () => {
  250. const AsyncChild = {
  251. async setup() {
  252. const count = ref(0)
  253. return () =>
  254. h(
  255. 'span',
  256. {
  257. onClick: () => {
  258. count.value++
  259. }
  260. },
  261. count.value
  262. )
  263. }
  264. }
  265. const { vnode, container } = mountWithHydration('<span>0</span>', () =>
  266. h(Suspense, () => h(AsyncChild))
  267. )
  268. expect(vnode.el).toBe(container.firstChild)
  269. // wait for hydration to finish
  270. await new Promise(r => setTimeout(r))
  271. triggerEvent('click', container.querySelector('span')!)
  272. await nextTick()
  273. expect(container.innerHTML).toBe(`<span>1</span>`)
  274. })
  275. test('Suspense (full integration)', async () => {
  276. const mountedCalls: number[] = []
  277. const asyncDeps: Promise<any>[] = []
  278. const AsyncChild = {
  279. async setup(props: { n: number }) {
  280. const count = ref(props.n)
  281. onMounted(() => {
  282. mountedCalls.push(props.n)
  283. })
  284. const p = new Promise(r => setTimeout(r, props.n * 10))
  285. asyncDeps.push(p)
  286. await p
  287. return () =>
  288. h(
  289. 'span',
  290. {
  291. onClick: () => {
  292. count.value++
  293. }
  294. },
  295. count.value
  296. )
  297. }
  298. }
  299. const done = jest.fn()
  300. const App = {
  301. template: `
  302. <Suspense @resolve="done">
  303. <AsyncChild :n="1" />
  304. <AsyncChild :n="2" />
  305. </Suspense>`,
  306. components: {
  307. AsyncChild
  308. },
  309. methods: {
  310. done
  311. }
  312. }
  313. const container = document.createElement('div')
  314. // server render
  315. container.innerHTML = await renderToString(h(App))
  316. expect(container.innerHTML).toMatchInlineSnapshot(
  317. `"<!--[--><span>1</span><span>2</span><!--]-->"`
  318. )
  319. // reset asyncDeps from ssr
  320. asyncDeps.length = 0
  321. // hydrate
  322. createSSRApp(App).mount(container)
  323. expect(mountedCalls.length).toBe(0)
  324. expect(asyncDeps.length).toBe(2)
  325. // wait for hydration to complete
  326. await Promise.all(asyncDeps)
  327. await new Promise(r => setTimeout(r))
  328. // should flush buffered effects
  329. expect(mountedCalls).toMatchObject([1, 2])
  330. expect(container.innerHTML).toMatch(`<span>1</span><span>2</span>`)
  331. const span1 = container.querySelector('span')!
  332. triggerEvent('click', span1)
  333. await nextTick()
  334. expect(container.innerHTML).toMatch(`<span>2</span><span>2</span>`)
  335. const span2 = span1.nextSibling as Element
  336. triggerEvent('click', span2)
  337. await nextTick()
  338. expect(container.innerHTML).toMatch(`<span>2</span><span>3</span>`)
  339. })
  340. test('async component', async () => {
  341. const spy = jest.fn()
  342. const Comp = () =>
  343. h(
  344. 'button',
  345. {
  346. onClick: spy
  347. },
  348. 'hello!'
  349. )
  350. let serverResolve: any
  351. let AsyncComp = createAsyncComponent(
  352. () =>
  353. new Promise(r => {
  354. serverResolve = r
  355. })
  356. )
  357. const App = {
  358. render() {
  359. return ['hello', h(AsyncComp), 'world']
  360. }
  361. }
  362. // server render
  363. const htmlPromise = renderToString(h(App))
  364. serverResolve(Comp)
  365. const html = await htmlPromise
  366. expect(html).toMatchInlineSnapshot(
  367. `"<!--[-->hello<button>hello!</button>world<!--]-->"`
  368. )
  369. // hydration
  370. let clientResolve: any
  371. AsyncComp = createAsyncComponent(
  372. () =>
  373. new Promise(r => {
  374. clientResolve = r
  375. })
  376. )
  377. const container = document.createElement('div')
  378. container.innerHTML = html
  379. createSSRApp(App).mount(container)
  380. // hydration not complete yet
  381. triggerEvent('click', container.querySelector('button')!)
  382. expect(spy).not.toHaveBeenCalled()
  383. // resolve
  384. clientResolve(Comp)
  385. await new Promise(r => setTimeout(r))
  386. // should be hydrated now
  387. triggerEvent('click', container.querySelector('button')!)
  388. expect(spy).toHaveBeenCalled()
  389. })
  390. describe('mismatch handling', () => {
  391. test('text node', () => {
  392. const { container } = mountWithHydration(`foo`, () => 'bar')
  393. expect(container.textContent).toBe('bar')
  394. expect(`Hydration text mismatch`).toHaveBeenWarned()
  395. })
  396. test('element text content', () => {
  397. const { container } = mountWithHydration(`<div>foo</div>`, () =>
  398. h('div', 'bar')
  399. )
  400. expect(container.innerHTML).toBe('<div>bar</div>')
  401. expect(`Hydration text content mismatch in <div>`).toHaveBeenWarned()
  402. })
  403. test('not enough children', () => {
  404. const { container } = mountWithHydration(`<div></div>`, () =>
  405. h('div', [h('span', 'foo'), h('span', 'bar')])
  406. )
  407. expect(container.innerHTML).toBe(
  408. '<div><span>foo</span><span>bar</span></div>'
  409. )
  410. expect(`Hydration children mismatch in <div>`).toHaveBeenWarned()
  411. })
  412. test('too many children', () => {
  413. const { container } = mountWithHydration(
  414. `<div><span>foo</span><span>bar</span></div>`,
  415. () => h('div', [h('span', 'foo')])
  416. )
  417. expect(container.innerHTML).toBe('<div><span>foo</span></div>')
  418. expect(`Hydration children mismatch in <div>`).toHaveBeenWarned()
  419. })
  420. test('complete mismatch', () => {
  421. const { container } = mountWithHydration(
  422. `<div><span>foo</span><span>bar</span></div>`,
  423. () => h('div', [h('div', 'foo'), h('p', 'bar')])
  424. )
  425. expect(container.innerHTML).toBe('<div><div>foo</div><p>bar</p></div>')
  426. expect(`Hydration node mismatch`).toHaveBeenWarnedTimes(2)
  427. })
  428. test('fragment mismatch removal', () => {
  429. const { container } = mountWithHydration(
  430. `<div><!--[--><div>foo</div><div>bar</div><!--]--></div>`,
  431. () => h('div', [h('span', 'replaced')])
  432. )
  433. expect(container.innerHTML).toBe('<div><span>replaced</span></div>')
  434. expect(`Hydration node mismatch`).toHaveBeenWarned()
  435. })
  436. test('fragment not enough children', () => {
  437. const { container } = mountWithHydration(
  438. `<div><!--[--><div>foo</div><!--]--><div>baz</div></div>`,
  439. () => h('div', [[h('div', 'foo'), h('div', 'bar')], h('div', 'baz')])
  440. )
  441. expect(container.innerHTML).toBe(
  442. '<div><!--[--><div>foo</div><div>bar</div><!--]--><div>baz</div></div>'
  443. )
  444. expect(`Hydration node mismatch`).toHaveBeenWarned()
  445. })
  446. test('fragment too many children', () => {
  447. const { container } = mountWithHydration(
  448. `<div><!--[--><div>foo</div><div>bar</div><!--]--><div>baz</div></div>`,
  449. () => h('div', [[h('div', 'foo')], h('div', 'baz')])
  450. )
  451. expect(container.innerHTML).toBe(
  452. '<div><!--[--><div>foo</div><!--]--><div>baz</div></div>'
  453. )
  454. // fragment ends early and attempts to hydrate the extra <div>bar</div>
  455. // as 2nd fragment child.
  456. expect(`Hydration text content mismatch`).toHaveBeenWarned()
  457. // exccesive children removal
  458. expect(`Hydration children mismatch`).toHaveBeenWarned()
  459. })
  460. })
  461. })