跳至主要內容

速查表

Vue Testing Library 中所有匯出函式的簡短指南。

查詢

與 DOM Testing Library 的差異

Vue Testing Library 中的 render 返回的查詢與 DOM Testing Library 相同。然而,它們的第一個參數綁定到文件,因此您寫的是 getByText('text') 而不是 getByText(node, 'text')

搜尋變體

若無匹配則返回若有 1 個匹配則返回若有 1 個以上匹配則返回需要等待?
getBy...拋出錯誤返回拋出錯誤
findBy...拋出錯誤返回拋出錯誤
queryBy...null返回拋出錯誤
getAllBy...拋出錯誤陣列陣列
findAllBy...拋出錯誤陣列陣列
queryAllBy...[]陣列陣列

搜尋類型

依據...尋找DOM 範例
...ByLabelTextlabel 或 aria-label 內容<label for="element" />
...ByPlaceholderText輸入框 placeholder 值<input placeholder="name" />
...ByText元素文字內容<p>Lorem ipsum</p>
...ByDisplayValue表單元素目前的值輸入元素的目前值
...ByAltTextimg alt 屬性<img alt="電影海報" />
...ByTitletitle 屬性或 svg title 標籤<span title="新增" /><title />
...ByRoleARIA role<div role="dialog" />
...ByTestIddata-testid 屬性<div data-testid="some-message" />

您可以寫出任何搜尋變體和搜尋類型的組合。

範例

getByLabelText('Username') 將搜尋包含字串 "Username" 的 <label> 元素,並返回相關聯的 input。如果找不到任何一個,或找到多個,則會拋出錯誤。

queryAllByRole('nav') 將同步尋找所有具有 role="nav" 屬性的元素,並返回包含結果的陣列(如果沒有找到結果,則返回空陣列)。

如需更多資訊,請參閱我應該使用哪個查詢?

非同步工具

  • waitFor (Promise) 重試函式直到停止拋出錯誤或逾時。
  • waitForElement (Promise) 重試函式或函式陣列並返回結果。
  • findByfindAllBy 查詢是非同步的,並會重試直到逾時或查詢成功返回;它們包裝了 waitForElement

如需更多資訊,請參閱DOM Testing Library 非同步 API

請記得在您的測試中 await.then() 非同步函式的結果!

觸發事件

  • fireEvent() 觸發 DOM 事件:fireEvent(node, event)
  • fireEvent.* 預設事件類型的輔助函式

如需更多資訊,請參閱事件 API

與 DOM Testing Library 的差異

Vue Testing Library 返回的事件都是非同步的,因此您應該 awaitthen() 結果。

VTL 也公開 fireEvent.update(node, value) 事件來處理 v-model。請參閱API 以取得更多詳細資訊。

其他

  • within(node) 取得一個節點並返回一個物件,其中包含所有綁定到該節點的查詢:within(getByTestId("global-header")).getByText("hello")
  • configure(config) 變更全域選項:configure({testIdAttribute: 'my-test-id'})

如需更多資訊,請參閱在元素內查詢Config API

文字匹配選項

假設有以下 HTML

<div>Hello World</div>

所有這些匹配器都將會找到元素:

// Matching a string:
getByText('Hello World') // full string match
getByText('llo Worl', {exact: false}) // substring match
getByText('hello world', {exact: false}) // ignore case

// Matching a regex:
getByText(/World/) // substring match
getByText(/world/i) // substring match, ignore case
getByText(/^hello world$/i) // full string match, ignore case
getByText(/Hello W?oRlD/i) // advanced regex

// Matching with a custom function:
getByText((content, element) => content.startsWith('Hello'))