Skip to content

测试服务器端渲染

¥Testing Server-side Rendering

Vue Test Utils 提供了 renderToString 来测试使用服务器端渲染(SSR)的 Vue 应用。本指南将引导你完成使用 SSR 测试 Vue 应用的过程。

¥Vue Test Utils provides renderToString to test Vue applications that use server-side rendering (SSR). This guide will walk you through the process of testing a Vue application that uses SSR.

renderToString

renderToString 是将 Vue 组件渲染为字符串的函数。它是一个返回 Promise 的异步函数,并接受与 mountshallowMount 相同的参数。

¥renderToString is a function that renders a Vue component to a string. It is an asynchronous function that returns a Promise, and accepts the same parameters as mount or shallowMount.

让我们考虑一个使用 onServerPrefetch 钩子的简单组件:

¥Let's consider a simple component that uses the onServerPrefetch hook:

ts
function fakeFetch(text: string) {
  return Promise.resolve(text)
}

const Component = defineComponent({
  template: '<div>{{ text }}</div>',
  setup() {
    const text = ref<string | null>(null)

    onServerPrefetch(async () => {
      text.value = await fakeFetch('onServerPrefetch')
    })

    return { text }
  }
})

你可以使用 renderToString 为此组件编写测试:

¥You can write a test for this component using renderToString:

ts
import { renderToString } from '@vue/test-utils'

it('renders the value returned by onServerPrefetch', async () => {
  const contents = await renderToString(Component)
  expect(contents).toBe('<div>onServerPrefetch</div>')
})

Vue Test Utils 中文网 - 粤ICP备13048890号