]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
test(ssr): computed with onServerPrefetch test/ssr-computed 9884/head
authorEduardo San Martin Morote <posva13@gmail.com>
Wed, 20 Dec 2023 16:09:13 +0000 (17:09 +0100)
committerEduardo San Martin Morote <posva13@gmail.com>
Wed, 20 Dec 2023 16:10:03 +0000 (17:10 +0100)
As noted in https://github.com/vuejs/core/issues/5300#issuecomment-1790432852

packages/server-renderer/__tests__/ssrComputed.spec.ts

index 52b45a63636880c9086f0bc1b2346b8c6378de42..df27c4e2fd373f56f995005ffee8a15c20b7b559 100644 (file)
@@ -1,4 +1,11 @@
-import { createSSRApp, defineComponent, h, computed, reactive } from 'vue'
+import {
+  createSSRApp,
+  defineComponent,
+  h,
+  computed,
+  reactive,
+  onServerPrefetch
+} from 'vue'
 import { renderToString } from '../src/renderToString'
 
 // #5208 reported memory leak of keeping computed alive during SSR
@@ -45,3 +52,42 @@ test('computed reactivity during SSR', async () => {
   // during the render phase
   expect(getterSpy).toHaveBeenCalledTimes(2)
 })
+
+test('computed reactivity during SSR with onServerPrefetch', async () => {
+  const store = {
+    // initial state could be hydrated
+    state: reactive({ items: null as null | string[] }),
+
+    // pretend to fetch some data from an api
+    async fetchData() {
+      this.state.items = ['hello', 'world']
+    }
+  }
+
+  const getterSpy = vi.fn()
+
+  const App = defineComponent(() => {
+    const msg = computed(() => {
+      getterSpy()
+      return store.state.items?.join(' ')
+    })
+
+    onServerPrefetch(() => store.fetchData())
+
+    // simulate the read from a composable (e.g. filtering a list of results)
+    msg.value
+
+    return () => h('div', null, msg.value)
+  })
+
+  const app = createSSRApp(App)
+
+  // in real world serve this html and append store state for hydration on client
+  const html = await renderToString(app)
+
+  expect(html).toMatch('hello world')
+
+  // should only be called twice since access should be cached
+  // during the render phase
+  expect(getterSpy).toHaveBeenCalledTimes(2)
+})