跳至主要內容

常見問題

另請參閱主要常見問題,以了解非特定於 Vue 測試的問題。

Vue Testing Library 可以取代官方的 @vue/test-utils 嗎?

簡短回答:是的,可以。如果您使用 Vue Testing Library (VTL),則無需安裝@vue/test-utils

較長的回答:VTL 是建立在 @vue/test-utils 之上的。官方函式庫用於呈現 Vue 組件(透過呼叫mount),並公開其某些方法(同時隱藏其他方法)。您可以在API 章節中查看可用方法的完整清單。

我需要安裝 DOM Testing Library 嗎?

不需要!VTL 從 DOM Testing Library 導入所有需要的內容,然後重新匯出。

Vue Testing Library 提供哪些查詢?

來自 DOM Testing Library 的所有查詢。有關完整清單,請參閱查詢

如果我不能使用淺層渲染,如何在測試中模擬組件?

一般來說,您應該避免模擬組件(請參閱指導原則章節)。

但是,如果需要,您可以使用 Jest 的模擬功能或 @vue/test-utils 提供的stubs鍵。

import {render} from '@testing-library/vue'
import Component from './Component'

test('Can stub components', () => {
render(Component, {
global: {stubs: ['FontAwesomeIcon']},
})
})

您可以在 VTL 的 GitHub 儲存庫中查看工作範例

如何測試元素是否已出現/已消失?

請查看指南的出現和消失章節,以了解可用於測試出現和消失的方法。

如果您想檢查元素是否從未渲染,您可能想撰寫類似以下內容

expect(queryByText('submit')).toBeNull()

// or, if using jest-dom:
import '@testing-library/jest-dom'
expect(queryByText('submit')).not.toBeInTheDocument()
為什麼我的 Vue Router 狀態似乎在測試之間共享?

預設情況下,Vue Router 使用hash 路由模式,該模式將路由更新儲存在 window.location 中。測試執行器(例如 Jest)不會在測試調用之間重置 JSDOM 環境,因此即使每次呼叫 render 時都會建立新的 Vue Router,先前測試中的路由轉換也可能會洩漏到後續測試中。

為了解決此問題,請使用 abstract 模式傳遞已實例化的路由器。abstract 模式不會將路由資訊儲存在 JSDOM window 上,因此路由資訊不會在測試之間洩漏。例如

import {render} from '@testing-library/vue'
import Component from './Component.vue'
import VueRouter from 'vue-router'

test('uses abstract mode for the router', async () => {
const router = new VueRouter({
mode: 'abstract',
routes: [
// Your routes here
],
})

const renderResult = render(Component, {
routes: router,
})

// Unlike the router in `hash` mode, the initial routing stack is empty. So,
// you need to push an initial route to the stack.
await router.push('/')
})

為了減少樣板程式碼,您可以建立一個自訂的渲染函式,以在整個測試套件中使用。例如

// test-utils.js

import {render} from '@testing-library/vue'
import VueRouter from 'vue-router'

export async function renderApp(component, options) {
const router = new VueRouter({
mode: 'abstract',
routes: [
// Your routes here
],
})

const renderResult = render(component, {
routes: router,
...options,
})

// Unlike the router in `hash` mode, the initial routing stack is empty. So,
// you need to push an initial route to the stack.
await router.push('/')

return renderResult
}