hydration.spec.ts 14 KB

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