速查表
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 範例 | |
---|---|---|
...ByLabelText | label 或 aria-label 內容 | <label for="element" /> |
...ByPlaceholderText | 輸入框 placeholder 值 | <input placeholder="name" /> |
...ByText | 元素文字內容 | <p>Lorem ipsum</p> |
...ByDisplayValue | 表單元素目前的值 | 輸入元素的目前值 |
...ByAltText | img alt 屬性 | <img alt="電影海報" /> |
...ByTitle | title 屬性或 svg title 標籤 | <span title="新增" /> 或 <title /> |
...ByRole | ARIA role | <div role="dialog" /> |
...ByTestId | data-testid 屬性 | <div data-testid="some-message" /> |
您可以寫出任何搜尋變體和搜尋類型的組合。
範例
getByLabelText('Username')
將搜尋包含字串 "Username" 的 <label>
元素,並返回相關聯的 input
。如果找不到任何一個,或找到多個,則會拋出錯誤。
queryAllByRole('nav')
將同步尋找所有具有 role="nav"
屬性的元素,並返回包含結果的陣列(如果沒有找到結果,則返回空陣列)。
如需更多資訊,請參閱我應該使用哪個查詢?。
非同步工具
- waitFor (Promise) 重試函式直到停止拋出錯誤或逾時。
- waitForElement (Promise) 重試函式或函式陣列並返回結果。
findBy
和findAllBy
查詢是非同步的,並會重試直到逾時或查詢成功返回;它們包裝了waitForElement
。
如需更多資訊,請參閱DOM Testing Library 非同步 API。
請記得在您的測試中
await
或.then()
非同步函式的結果!
觸發事件
- fireEvent() 觸發 DOM 事件:
fireEvent(node, event)
- fireEvent.* 預設事件類型的輔助函式
- click
fireEvent.click(node)
- input
fireEvent.input(node, event)
- 查看所有支援的事件
- click
如需更多資訊,請參閱事件 API
與 DOM Testing Library 的差異
從
Vue Testing Library
返回的事件都是非同步的,因此您應該await
或then()
結果。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'))