hydration.spec.ts 12 KB

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