Skip to content

Commit

Permalink
feat: add renderToString function
Browse files Browse the repository at this point in the history
It is now possible to use `renderToString` to test the SSR rendering of a component.

To do so, use `renderToString(MyComponent)`.
`renderToString` returns a `Promise<string>` with the HTML rendered.

```ts
  it('returns correct html with pre-fetched data on server', async () => {
    const Component = defineComponent({
      template: '<div>{{ text }}</div>',
      setup() {
        const text = ref<string | null>(null)
        onServerPrefetch(async () => {
          text.value = await fakeFetch('onServerPrefetch')
        })
        return { text }
      }
    })

    const contents = await renderToString(Component)

    expect(contents).toBe('<div>onServerPrefetch</div>')
  })
```
  • Loading branch information
wobsoriano authored and cexbrayat committed Feb 10, 2023
1 parent 85c0a87 commit 9af6455
Show file tree
Hide file tree
Showing 7 changed files with 799 additions and 351 deletions.
40 changes: 40 additions & 0 deletions docs/guide/advanced/ssr.md
@@ -0,0 +1,40 @@
# Testing Server-side Rendering

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` 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`.

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 }
}
})
```

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

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

0 comments on commit 9af6455

Please sign in to comment.