Puppeteer 测试库
pptr-testing-library
是一个轻量级适配器,允许将 DOM 测试库
用于 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('[email protected]')
// waiting works too!
await waitFor(() => getByText('Loading...'))
对你来说太不 puppeteer 了?你可以将所有 DOM 测试库
方法直接附加到 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 测试库
中没有的独特方法。
getDocument(page: puppeteer.Page): ElementHandle
- 获取文档的 ElementHandle
转发方法
DOM 测试库
被注入到 puppeteer 控制的页面中,每次查询都会被注入,因此所有结果都是异步的。仍然建议您使用 puppeteer 的内置方法进行交互,而不是 fireEvent
。
已知限制
waitForElement
方法没有公开。Puppeteer 有自己的一套等待实用程序,与DOM 测试库
中使用的样式有些冲突。请参见 GitHub 上的问题。fireEvent
方法没有公开,请改用 puppeteer 的内置方法。expect
断言扩展不可用。