You’re browsing the documentation for Vue Test Utils for Vue v2.x and earlier.
To read docs for Vue Test Utils for Vue 3, click here.
renderToString()
参数:
{Component} component
{Object} options
{Object} context
{Array<Component|Object>|Component} children
{Object} slots
{Array<Component|Object>|Component|String} default
{Array<Component|Object>|Component|String} named
{Object} mocks
{Object|Array<string>} stubs
{Vue} localVue
返回值:
{Promise<string>}
选项:
查阅挂载选项
- 使用:
将一个组件渲染为 HTML。
renderToString
在底层使用 vue-server-renderer
将一个组件渲染为 HTML。
不带选项:
import { renderToString } from '@vue/server-test-utils'
import Foo from './Foo.vue'
describe('Foo', () => {
it('renders a div', async () => {
const str = await renderToString(Foo)
expect(str).toContain('<div></div>')
})
})
带 Vue 选项:
import { renderToString } from '@vue/server-test-utils'
import Foo from './Foo.vue'
describe('Foo', () => {
it('renders a div', async () => {
const str = await renderToString(Foo, {
propsData: {
color: 'red'
}
})
expect(str).toContain('red')
})
})
默认插槽和具名插槽:
import { renderToString } from '@vue/server-test-utils'
import Foo from './Foo.vue'
import Bar from './Bar.vue'
import FooBar from './FooBar.vue'
describe('Foo', () => {
it('renders a div', async () => {
const str = await renderToString(Foo, {
slots: {
default: [Bar, FooBar],
fooBar: FooBar, // Will match <slot name="FooBar" />,
foo: '<div />'
}
})
expect(str).toContain('<div></div>')
})
})
全局属性存根:
import { renderToString } from '@vue/server-test-utils'
import Foo from './Foo.vue'
describe('Foo', () => {
it('renders a div', async () => {
const $route = { path: 'http://www.example-path.com' }
const str = await renderToString(Foo, {
mocks: {
$route
}
})
expect(str).toContain($route.path)
})
})