Puppeteer 測試函式庫
pptr-testing-library
是一個輕量級的轉接器,允許將 DOM Testing Library
與 puppeteer
一起使用。
- npm
- Yarn
npm install --save-dev puppeteer pptr-testing-library
yarn add --dev puppeteer pptr-testing-library
用法
const puppeteer = require('puppeteer')
const {getDocument, queries, waitFor} = require('pptr-testing-library')
const {getByTestId, getByLabelText} = queries
const browser = await puppeteer.launch()
const page = await browser.newPage()
// Grab ElementHandle for document
const $document = await getDocument(page)
// Your favorite query methods are available
const $form = await getByTestId($document, 'my-form')
// returned elements are Puppeteer ElementHandles too!
const $email = await getByLabelText($form, 'Email')
// interact with puppeteer like usual
await $email.type('pptr@example.com')
// waiting works too!
await waitFor(() => getByText('Loading...'))
覺得有點太不像是 Puppeteer 的風格嗎?您可以將所有 DOM Testing Library
的方法直接附加到 Puppeteer 的 ElementHandle
上!
const puppeteer = require('puppeteer')
require('pptr-testing-library/extend')
const browser = await puppeteer.launch()
const page = await browser.newPage()
// getDocument is added to prototype of Page
const $document = await page.getDocument()
// query methods are added directly to prototype of ElementHandle
const $form = await $document.getByTestId('my-form')
// destructuring works if you explicitly call getQueriesForElement
const {getByLabelText} = $form.getQueriesForElement()
// ...
const $email = await getByLabelText('Email')
API
獨特的方法,不屬於 DOM Testing Library
的一部分。
getDocument(page: puppeteer.Page): ElementHandle
- 取得文件的 ElementHandle
轉發的方法
DOM Testing Library
會在每次查詢時被注入到 Puppeteer 控制的頁面中,因此所有結果都會是異步的。仍然建議您使用 Puppeteer 的內建方法進行互動,而不是 fireEvent
。
已知限制
waitForElement
方法未公開。Puppeteer 有自己的一組等待工具,這與DOM Testing Library
中使用的樣式有些衝突。請參閱 GitHub 上的議題。fireEvent
方法未公開,請改用 Puppeteer 的內建方法。expect
斷言擴充功能不可用。