Stubs 與 ShallowMount
Vue Test Utils 提供一些進階功能來為元件和指令建立替身(stub)。替身是指你用一個什麼都不做的虛擬實作來取代現有的自定義元件或指令實作,這可以簡化原本複雜的測試。讓我們來看個例子。
為單一子元件建立替身
常見的例子是當你想測試元件階層中很高層級的某個元件時。
在這個例子中,我們有一個 <App>
會渲染訊息,以及一個 FetchDataFromApi
元件會呼叫 API 並渲染結果。
const FetchDataFromApi = {
name: 'FetchDataFromApi',
template: `
<div>{{ result }}</div>
`,
async mounted() {
const res = await axios.get('/api/info')
this.result = res.data
},
data() {
return {
result: ''
}
}
}
const App = {
components: {
FetchDataFromApi
},
template: `
<h1>Welcome to Vue.js 3</h1>
<fetch-data-from-api />
`
}
在這個特定測試中,我們不想真的呼叫 API,只想斷言訊息有被渲染。這時可以使用全域掛載選項中的 stubs
。
test('stubs component with custom template', () => {
const wrapper = mount(App, {
global: {
stubs: {
FetchDataFromApi: {
template: '<span />'
}
}
}
})
console.log(wrapper.html())
// <h1>Welcome to Vue.js 3</h1><span></span>
expect(wrapper.html()).toContain('Welcome to Vue.js 3')
})
注意到 template 在 <fetch-data-from-api />
的位置顯示了 <span></span>
嗎?我們用替身取代了它,在這個例子中我們提供自己的實作,傳入一個 template。
你也可以使用預設替身,而不用提供自己的:
test('stubs component', () => {
const wrapper = mount(App, {
global: {
stubs: {
FetchDataFromApi: true
}
}
})
console.log(wrapper.html())
/*
<h1>Welcome to Vue.js 3</h1>
<fetch-data-from-api-stub></fetch-data-from-api-stub>
*/
expect(wrapper.html()).toContain('Welcome to Vue.js 3')
})
這會在整個渲染樹中為所有 <FetchDataFromApi />
元件建立替身,不論它們出現在哪一層。這就是為什麼它在全域掛載選項中。
提示
要建立替身,你可以使用 components 中的 key 或元件的 name。如果兩者都在 global.stubs 中,會優先使用 key。