Helpers for working with the DOM, useful for tests.
npm i -D @bicycle-codes/dom
import { dom } from '@bicycle-codes/dom'
// or import individual functions
import { waitFor } from '@bicycle-codes/dom'
const dom = require('@bicycle-codes/dom').dom
dom.qs
points to document.querySelector
dom.qsa
is equal to document.querySelectorAll
Look for a DOM element by slector. Default timeout is 5 seconds. Throws if the element is not found.
function waitFor (args:{
selector?:string,
visible?:boolean,
timeout?:number
}|string, lambda?:() => Element|null):Promise<Element>
import { waitFor } from '@bicycle-codes/dom'
const foundElement = await waitFor({
selector: 'p'
})
// or pass in a string to use as a query selector
const el = await waitFor('#my-element')
Look for an element containing the given text, or that matches a given regex. Return the element if found. Default timeout is 5 seconds. Throws if the element is not found.
function waitForText (args:{
text?:string,
timeout?:number,
element:Element,
multipleTags?:boolean,
regex?:RegExp
}):Promise<Element>
import { waitForText } from '@bicycle-codes/dom'
const el = await waitForText({
element: document.body,
regex: /bar/
})
Pass in a parent element and timeout.
const found = await waitForText({
element: dom.qs('#test-two'),
multipleTags: true,
text: 'bbb',
timeout: 10000 // 10 seconds
})
Dispatch a click event from the given element.
import { dom } from '@bicycle-codes/dom'
// or import { click } from '@bicycle-codes/dom'
dom.click(dom.qs('#my-element'))
Dispatch an event from an element.
function event (args:{
event:string|Event;
element?:HTMLElement|Element|typeof window
}):void
import { dom } from '@bicycle-codes/dom'
dom.event({ event: 'hello', element: dom.qs('#example') })
Wait for the given milliseconds.
async function sleep (ms:number):Promise<void>
import { sleep } from '@bicycle-codes/dom'
await sleep(3000) // wait 3 seconds
Thanks Jake Verbaten for writing this originally.