跳至主要內容

出現與消失

有時您需要測試元素是否存在,然後消失,反之亦然。

等待出現

如果您需要等待元素出現,非同步等待工具允許您等待斷言滿足後再繼續。等待工具會重試,直到查詢通過或逾時。非同步方法會返回 Promise,因此在呼叫它們時必須始終使用 await.then(done)

1. 使用 findBy 查詢

test('movie title appears', async () => {
// element is initially not present...
// wait for appearance and return the element
const movie = await findByText('the lion king')
})

2. 使用 waitFor

test('movie title appears', async () => {
// element is initially not present...

// wait for appearance inside an assertion
await waitFor(() => {
expect(getByText('the lion king')).toBeInTheDocument()
})
})

等待消失

waitForElementToBeRemoved 非同步輔助函數使用回呼在每個 DOM 變更時查詢元素,並在元素移除時解析為 true

test('movie title no longer present in DOM', async () => {
// element is removed
await waitForElementToBeRemoved(() => queryByText('the mummy'))
})

使用 MutationObserver 比使用 waitFor 定期輪詢 DOM 更有效率。

waitFor 非同步輔助函數會重試,直到包裝的函數停止拋出錯誤。這可以用來斷言元素從頁面消失。

test('movie title goes away', async () => {
// element is initially present...
// note use of queryBy instead of getBy to return null
// instead of throwing in the query itself
await waitFor(() => {
expect(queryByText('i, robot')).not.toBeInTheDocument()
})
})

斷言元素不存在

標準的 getBy 方法在找不到元素時會拋出錯誤,因此如果您想斷言元素存在於 DOM 中,可以使用 queryBy API 取代

const submitButton = screen.queryByText('submit')
expect(submitButton).toBeNull() // it doesn't exist

queryAll API 版本會返回一個匹配節點的陣列。該陣列的長度對於在元素新增或從 DOM 移除後進行斷言很有用。

const submitButtons = screen.queryAllByText('submit')
expect(submitButtons).toHaveLength(0) // expect no elements

not.toBeInTheDocument

jest-dom 工具庫提供了 .toBeInTheDocument() 匹配器,可以用來斷言元素是否存在於文件的 body 中,或不存在。這比斷言查詢結果為 null 更具意義。

import '@testing-library/jest-dom'
// use `queryBy` to avoid throwing an error with `getBy`
const submitButton = screen.queryByText('submit')
expect(submitButton).not.toBeInTheDocument()