|
| 1 | +# `renderToString(component {, options}])` |
| 2 | + |
| 3 | +- **引数:** |
| 4 | + |
| 5 | + - `{Component} component` |
| 6 | + - `{Object} options` |
| 7 | + - `{Object} context` |
| 8 | + - `{Array<Component|Object>|Component} children` |
| 9 | + - `{Object} slots` |
| 10 | + - `{Array<Componet|Object>|Component|String} default` |
| 11 | + - `{Array<Componet|Object>|Component|String} named` |
| 12 | + - `{Object} mocks` |
| 13 | + - `{Object|Array<string>} stubs` |
| 14 | + - `{Vue} localVue` |
| 15 | + |
| 16 | +- **戻り値:** `{string}` |
| 17 | + |
| 18 | +- **オプション:** |
| 19 | + |
| 20 | +[オプション](./options.md)を参照してください。 |
| 21 | + |
| 22 | +- **使い方:** |
| 23 | + |
| 24 | +コンポーネントをHTMLにレンダリングします。 |
| 25 | + |
| 26 | +コンポーネントをHTMLにレンダリングするために、`renderToString` は内部で [`vue-server-renderer`](https://ssr.vuejs.org/en/basic.html) を使用します。 |
| 27 | + |
| 28 | +**オプションなし:** |
| 29 | + |
| 30 | +```js |
| 31 | +import { renderToString } from '@vue/test-utils' |
| 32 | +import Foo from './Foo.vue' |
| 33 | + |
| 34 | +describe('Foo', () => { |
| 35 | + it('renders a div', () => { |
| 36 | + const renderedString = renderToString(Foo) |
| 37 | + expect(renderedString).toContain('<div></div>') |
| 38 | + }) |
| 39 | +}) |
| 40 | +``` |
| 41 | + |
| 42 | +**Vueオプションを使用:** |
| 43 | + |
| 44 | +```js |
| 45 | +import { renderToString } from '@vue/test-utils' |
| 46 | +import Foo from './Foo.vue' |
| 47 | + |
| 48 | +describe('Foo', () => { |
| 49 | + it('renders a div', () => { |
| 50 | + const renderedString = renderToString(Foo, { |
| 51 | + propsData: { |
| 52 | + color: 'red' |
| 53 | + } |
| 54 | + }) |
| 55 | + expect(renderedString).toContain('red') |
| 56 | + }) |
| 57 | +}) |
| 58 | +``` |
| 59 | + |
| 60 | +**デフォルトおよび名前付きスロット:** |
| 61 | + |
| 62 | +```js |
| 63 | +import { renderToString } from '@vue/test-utils' |
| 64 | +import Foo from './Foo.vue' |
| 65 | +import Bar from './Bar.vue' |
| 66 | +import FooBar from './FooBar.vue' |
| 67 | + |
| 68 | +describe('Foo', () => { |
| 69 | + it('renders a div', () => { |
| 70 | + const renderedString = renderToString(Foo, { |
| 71 | + slots: { |
| 72 | + default: [Bar, FooBar], |
| 73 | + fooBar: FooBar, // <slot name="FooBar" /> にマッチします。 |
| 74 | + foo: '<div />' |
| 75 | + } |
| 76 | + }) |
| 77 | + expect(renderedString).toContain('<div></div>') |
| 78 | + }) |
| 79 | +}) |
| 80 | +``` |
| 81 | + |
| 82 | +**グローバルプロパティをスタブする:** |
| 83 | + |
| 84 | +```js |
| 85 | +import { renderToString } from '@vue/test-utils' |
| 86 | +import Foo from './Foo.vue' |
| 87 | + |
| 88 | +describe('Foo', () => { |
| 89 | + it('renders a div', () => { |
| 90 | + const $route = { path: 'http://www.example-path.com' } |
| 91 | + const renderedString = renderToString(Foo, { |
| 92 | + mocks: { |
| 93 | + $route |
| 94 | + } |
| 95 | + }) |
| 96 | + expect(renderedString).toContain($route.path) |
| 97 | + }) |
| 98 | +}) |
| 99 | +``` |
0 commit comments