Skip to content

CDPBrowser

Extends Helper

CDPBrowser drives a browser directly over the raw Chrome DevTools Protocol, without depending on Puppeteer, Playwright, or WebDriver. It opens its own WebSocket connection (via CDPConnection), creates and attaches to a fresh target per test, and evaluates expressions through Runtime.evaluate.

It is intended as the minimal, dependency-light base class for helpers that only need navigation, script evaluation, and simple in-page element interaction (installed lazily through the window.__codecept client script). It does not launch a browser itself — point endpoint at an already-running Chrome (or any CDP-compatible browser) started with --remote-debugging-port.

// inside codecept.conf.js
{
helpers: {
CDPBrowser: {
url: 'http://localhost',
endpoint: 'http://127.0.0.1:9222',
}
}
}

This helper should be configured in codecept.conf.js

Type: object

  • url string? base url of website to be tested.
  • endpoint string? Chrome DevTools Protocol endpoint. Either an http(s):// address exposing /json/version (from which the webSocketDebuggerUrl is resolved) or a raw ws(s):// debugger URL.
  • headers object? headers sent with the endpoint resolution request and the WebSocket handshake. Useful for authenticated remote browser providers.
  • input string? how synthetic user actions (click, fill, etc.) are dispatched by helpers built on top of this class. auto picks cdp when a real layout engine is detected and synthetic otherwise; can be pinned to cdp or synthetic.
  • xpathPolyfill (string | boolean)? whether to inject the bundled XPath polyfill before installing the in-page client. auto probes the page and only injects when document.evaluate is unavailable or broken; true/false force the behavior.
  • capabilities object? pre-seed detected browser capabilities (layout, xpath, screenshot, innerText) to skip runtime probing. Values set here are never overwritten by _probeCapabilities/_ensureClient.
  • waitForTimeout number? default wait* timeout in seconds, used by helpers built on top of this class.
  • waitForAction number? only takes effect when set explicitly: a literal fixed pacing sleep (in milliseconds) after click, type, or other interactions, mirroring other browser helpers. Left unset, actions settle in an event-aware way instead — near-instant when nothing navigates, waiting for the navigation to actually finish (not a guessed fixed delay) when one does.
  • pollInterval number? interval in milliseconds between retries while polling for a condition (e.g. page ready state, waitFor*). Distinct from waitForAction.
  • getPageTimeout number? maximum time in seconds to wait for a page to finish loading after navigation or reload; also used as the CDP command timeout (in ms, x1000).
  • waitForNavigation string? when to consider a navigation finished: load, domcontentloaded, or networkidle. Mirrors the Puppeteer helper’s option name. networkidle waits for the CDP networkIdle lifecycle event, which on a busy page can lag load by a second or more — only opt in if the extra wait is actually needed.
  • config CDPBrowserConfig

Hook executed after each test. Closes the target opened in _before via Target.closeTarget and clears this.targetId/this.sessionId. The underlying CDPConnection is left open so it can be reused by the next test.

Arms the event-aware settle’s navigation-start listener. Must be called before the action that might trigger a navigation is dispatched, not after — see _ensureLifecycleListener for why. Returns null when options.waitForAction was set explicitly, since _waitForAction ignores the armed listener entirely in that case (a literal fixed sleep, as before this round).

No timeout here: _waitForAction applies the grace window itself, starting from when it runs (after the action’s own dispatch already resolved), racing this already-armed listener against a fresh timer instead of one that started ticking before the action even began.

Returns ({promise: Promise<(string | null)>, cancel: function} | null)

Throws if the current page has no real layout engine (capabilities.layout === 'none'), used to guard visibility-dependent assertions that cannot be evaluated without one.

  • action string name of the calling assertion, used in the error message.
  • Throws Error if the page has no layout engine.

Hook executed before each test. Ensures a live CDPConnection exists (connecting lazily on first use, and reconnecting if a previous connection was closed), then creates a fresh about:blank target and attaches to it with Target.attachToTarget, storing this.targetId and this.sessionId. Page and Runtime domains are enabled on the new session, and engine capabilities are probed here (against about:blank, uncontended) rather than only lazily on the first real page — see _probeCapabilities.

Also resets _navStartWaiters and _lastMainFrameNav: both are scoped to a single sessionId/targetId, which are about to change, so anything left over from the previous test (e.g. an action-settle waiter still armed because its test threw between arming and settling) can never legitimately resolve against the new session — better to drop it here than leave it waiting for the rest of the run.

Builds the list of {type, value} candidates _run should try, in order, for a given locator and kind. A strict locator (CSS/XPath/object form) resolves to a single candidate. A fuzzy (plain-text) locator is expanded into a strategy-specific list of XPath expressions mirroring the click/field/checkbox matching used by other browser helpers (matching by visible text, label, name, placeholder, ARIA attributes, etc.), falling back to treating the raw text as a CSS selector.

A role locator ({role, text, exact}) resolves to a single role-type candidate, resolved in-page by the client’s implicit ARIA role mapping (native elements) plus explicit role attributes, filtered by accessible name/text when text is given.

  • locator (string | object) element located by CSS|XPath|strict locator, or plain fuzzy text.
  • kind ("element" | "clickable" | "field" | "checkable") matching strategy to use when locator is fuzzy.

A short, human-readable label built from candidates, used in _run’s elementIndex/strict error messages when no locator string is otherwise available.

  • candidates

Returns string

Whether any candidate strategy — in candidates itself, or in any of the within scoping layers searched before it — is an xpath locator. Used to decide, before the client is even installed, whether the XPath polyfill needs to be bundled into that install or can be deferred.

Returns boolean

Shared implementation for see/dontSee. Without a context locator and outside any within block, checks presence via _runTextCheck’s fast, boolean-only round trip; the full haystack is only fetched (one extra, rare evaluate) when the assertion is about to fail, to build the same stringIncludes error as before this optimization. With a context or inside within, this is unchanged from before — already a small, per-element read, not the identified cost.

Returns Promise

Resolves the CDP endpoint and opens the underlying CDPConnection, storing it on this.cdp.

Ensures the in-page client (window.__codecept, installed from cdpBrowserClient.js) is present on the current page, installing it (and the XPath polyfill, if needed) exactly once. Safe to call repeatedly; it is a no-op once the client is detected.

Lazily installs a single, persistent Page.lifecycleEvent listener on the underlying CDPConnection and drains it into whichever _waitForLoadEvent calls are currently pending, matched by loaderId. Installed once per helper instance (the connection outlives individual tests), never removed — CDPConnection has no listener-removal API, so a single persistent dispatcher (rather than one listener per navigation) is what keeps this leak-free.

Also, for the main frame (params.frameId === this.targetId, which holds for a page target’s own top-level frame) only:

  • Drains _navStartWaiters (armed by _armActionSettle, before an action, for _waitForAction’s event-aware settle) on an 'init' event — confirmed via a raw probe (against both Obscura and Chrome, through the actual CLI path) to be the earliest signal CDP emits when a new top-level navigation begins. Arming happens before the action is dispatched, not after: the same probe found 'init' can arrive while the action’s own CDP round trip is still in flight, sometimes only a millisecond or two after it started — a listener installed only once the action’s promise resolves can already be too late, not merely unlucky.
  • Maintains _lastMainFrameNav, a rolling {loaderId, events} record of every lifecycle event name seen for the current main-frame navigation (reset whenever loaderId changes). On a fast/local navigation, the same raw probe found the entire sequence — init through networkIdle — arriving as one batch while the triggering action’s own round trip was still in flight. Without this cache, _waitForAction would correctly detect that a navigation started, then arm a fresh wait for the load event specifically — which, in that common case, had already fired and will never fire again, paying the full grace-window-plus-poll cost of _waitForPageLoad on every single navigating action instead of settling immediately.

Evaluates a JavaScript expression in the page attached to the current session via Runtime.evaluate, awaiting any returned promise and returning the value by reference (returnByValue: true). If the expression throws, the browser-side exception description (or fallback text) is re-thrown as a JS Error.

  • expression string a JavaScript expression (or IIFE) to run in the page context.

Returns Promise the evaluated value, or undefined if the expression has no result.

Hook executed after all tests are run. Closes the underlying CDPConnection (and its WebSocket) and clears this.cdp. Must leave no open sockets or pending timers behind, so the process can exit on its own.

Resolves the current page URL to a pathname, ignoring the origin, query string, and hash.

Returns Promise<string> the pathname of the current page.

Brings the current target to front and grants it clipboard read/write access, so navigator.clipboard does not reject with a permission or focus error. Failures are ignored: a browser without Browser.grantPermissions surfaces its own error from the read instead.

No-op hook kept for interface parity with other browser helpers. Connecting to the CDP endpoint is deferred to _before, since a fresh target/session is opened per test.

Installs the in-page client unconditionally — no typeof window.__codecept presence check. Used by callers that already know, from a sentinel value returned alongside a failed action, that the client is missing on the current page, so re-checking would just be a redundant contended round trip.

The 171KB XPath polyfill is only injected alongside the client when needsXPath is true (the default, for callers without candidate information) and the engine actually needs it (capabilities.xpath === 'polyfill', cached from _before’s probe). Callers that know their candidates never resolve to an xpath strategy (e.g. _runSelected, once it has inspected candidates/within) can pass false to skip that inject — the client is still told, via the xpathNeedsPolyfill flag baked in at install time, that the engine will eventually need it, so a later call that does hit an xpath candidate gets a clean '__NO_XPATH__' miss signal (from window.__codecept.run) instead of silently falling through to a broken native document.evaluate_runSelected reacts to that sentinel by injecting the polyfill and retrying once, mirroring the '__NO_CLIENT__' handling right next to it.

Determines whether see/dontSee/waitForText should read whole-page text through the client’s own visibility-aware visibleText() walker instead of the native document.body.innerText. Probes once per page by appending a display:none element and a <script> element, each with distinguishing text, and checking that native innerText excludes both — some engines return an innerText that does not honor computed visibility or exclude script/style content, even when getComputedStyle/layout are otherwise reliable. The result is cached on capabilities.innerText ('native' or 'computed').

Returns Promise<boolean> true if the visibleText() fallback should be used.

Determines whether the bundled XPath polyfill must be injected before the in-page client is installed. Honors an explicit options.xpathPolyfill boolean; otherwise reuses a previously probed capabilities.xpath, or probes the page’s native document.evaluate. The probe appends two throwaway elements distinguished only by text content and asserts that a text-value XPath predicate (normalize-space(string(.))=..., the basis of every fuzzy/clickable locator) resolves to exactly the matching one — merely checking that document.evaluate runs without throwing is not enough, since some engines execute a text-value predicate without actually filtering by it, silently returning every candidate node instead of none or one. The result is cached on capabilities.xpath ('native' or 'polyfill').

Returns Promise<boolean> true if the polyfill should be injected.

Page.screencastFrame handler: ignores frames from a session other than the currently active one (stale frames from a previous test, since the listener is never removed), acknowledges the frame so the browser keeps sending more, and buffers {data, timestamp} for stopScreencast to assemble.

  • params
  • sessionId

Network.loadingFailed handler, resolving a still-pending response promise to null (matching Puppeteer’s request.response() for a failed request) so grabRecordedNetworkTraffics never awaits a promise that would otherwise never settle.

  • params
  • sessionId

Network.requestWillBeSent handler, pushed into this.requests when it belongs to the currently active session and recording is on.

  • params
  • sessionId

Network.responseReceived handler, resolving the matching pending response promise pushed by _onTrafficRequest with a Puppeteer-HTTPResponse-like object.

  • params
  • sessionId

Repeatedly calls fn until it returns a truthy value or timeoutSec elapses, checking immediately and waiting options.pollInterval milliseconds between subsequent attempts.

  • fn function the condition to poll; should resolve to a truthy value once satisfied.
  • timeoutSec number maximum time to poll, in seconds.
  • message string error message used when the timeout is reached.
  • cancelToken {cancelled: boolean}?? when cancelled becomes true (set by the caller from outside), polling stops early with an error instead of continuing to timeoutSec. Used by _waitForPageLoad to tear down the losing side of a race instead of leaving it running.
  • Throws Error with message if timeoutSec elapses without fn returning a truthy value, or a cancellation error if cancelToken.cancelled is set first.

Returns Promise the truthy value returned by fn.

Probes and caches capabilities that depend on the actual browser engine rather than any particular page’s content: capabilities.layout (via getComputedStyle), capabilities.screenshot (inferred from layout), capabilities.xpath (via _needsXPathPolyfill), and capabilities.innerText (via _needsVisibleTextFallback). Already-known capabilities (pre-seeded through options.capabilities, or probed earlier) are never re-probed — so, across a whole run, this issues a handful of _evaluate calls exactly once and is a no-op afterward.

Called from _before, against the fresh about:blank target created there, specifically so these probes run before any real navigation — measured directly (a full stall ledger against github.com) that running them on the first real page instead can cost seconds each, since every one is an _evaluate competing with that page’s own JavaScript for the V8 isolate. about:blank has no such competition. Also called (cheaply, already cached by then) from amOnPage, so a helper that skips _before for some reason still probes correctly.

The xpath/innerText probes determine whether their respective fallback is needed; they do not install anything — injection stays deferred to _ensureClient’s reactive install and _textSource’s own read, matching amOnPage no longer eagerly installing the client.

Resolves options.endpoint to a raw WebSocket debugger URL. If the configured endpoint is an http(s):// address, this fetches /json/version from it and reads webSocketDebuggerUrl from the response, matching the discovery flow exposed by Chrome’s --remote-debugging-port. A ws(s):// endpoint is returned unchanged.

This is the subclass override point for helpers that connect through a different discovery mechanism (e.g. a cloud browser provider with its own session-creation API).

Returns Promise<string> a ws(s):// debugger URL ready to be passed to CDPConnection.

Delegates a find-and-act call to window.__codecept.run(candidates, action, payload). This is the primary extension point used by helpers built on top of this class for element queries and interactions.

A per-call context locator, when given, is resolved and layered on top of any active within block (searched inside it, not instead of it), so context narrows the search without breaking out of a surrounding within.

  • candidates
  • action string name of the action to run against the matched elements (e.g. count, click, fill).
  • payload object? extra data the action needs (e.g. { value } for fill).
  • context (string? | object) element to search in, narrowing the candidates below it.

Returns Promise<{found: number, result: any}> number of matched elements and the action’s result.

Same as _run, but takes an explicit selection descriptor instead of reading one from store.currentStep/options.strict. Used internally by CDPElementHandle to address one specific element out of a candidate set by its 1-based index.

The in-page client’s presence is checked in the same round-trip as the action itself: the evaluated expression resolves to a sentinel string when window.__codecept is missing (e.g. right after a navigation the registered script didn’t reach), in which case the client is installed and the call is retried exactly once. Separately, if the client is already present but reports (via its own '__NO_XPATH__' sentinel) that this call needs the XPath polyfill and it was not bundled into that earlier install, the polyfill is injected and the call is retried once more — see _installClient.

  • candidates
  • action string
  • payload (object | null)
  • selection (object | null) {index} or {strict: true}, mirroring _selectionDescriptor.
  • context (string? | object)

Returns Promise<{found: number, result: any}>

Runs the in-page containsText check against the whole page (no context/within scoping — those stay on _textSource’s per-element path, already small). Returns only {found, snippet} instead of the full haystack: on a page with a large body, serializing that whole string across the CDP wire (and, on engines where capabilities.innerText requires the visibleText() walker, holding it in memory) is avoidable work see/dontSee/waitForText don’t actually need on their common, non-throwing path.

Also folds the client’s install into the very same round trip when it is still missing, instead of a separate presence-check evaluate followed by an install evaluate before the check itself can even run — mirroring _runSelected’s sentinel-retry design, but collapsed into one evaluate since the install source itself is known and cacheable up front. That install is client-only, never the 171KB XPath polyfill: containsText never calls document.evaluate, so bundling it here would be pure waste for a scenario that never resolves an xpath locator. The client is still told, via installCodeceptClient’s xpathNeedsPolyfill flag, whether the engine (capabilities.xpath, cached by _before’s about:blank probe) will eventually need it, so a later xpath-resolving action on the same page gets a clean '__NO_XPATH__' miss signal from window.__codecept.run instead of silently hitting a broken native document.evaluate_runSelected reacts to that sentinel already. The bootstrap source is built once and reused for the life of the instance, since whether the engine needs the polyfill never changes.

Returns Promise<{found: boolean, snippet: (string | null)}>

Shared implementation for seeInField/dontSeeInField.

Returns Promise

Builds the {index, strict} element-selection descriptor from the current step’s options (store.currentStep.opts) and options.strict, mirroring the semantics of lib/helper/extras/elementSelection.js (used by Puppeteer/WebDriver): a per-step elementIndex (numeric, or the 'first'/'last' aliases) always takes precedence and disables strict mode for that step; otherwise exact/strictMode per-step options override options.strict to enable or cancel strict mode.

Returns (object | null) descriptor with optional index and strict keys, or null when neither applies.

Resolves whether the texts action should read via the client’s visibleText() walker (probed once via _needsVisibleTextFallback and cached on capabilities.innerText) instead of each element’s native innerText, then runs it.

Returns Promise<{found: number, result: any}>

Resolves the text to search see/dontSee/waitForText against, when no explicit context locator is given. An explicit context is always resolved through _run, so it is implicitly scoped to the active within block, if any. Without a context, this reads the within root’s text when a within block is active, or the whole page’s text otherwise — via native document.body.innerText, or the client’s visibleText() walker when _needsVisibleTextFallback determines native innerText is not trustworthy.

Returns Promise<string>

Resolves a path against options.url. Absolute URLs (matching scheme://) are returned unchanged; anything else is appended to options.url with its trailing slash stripped.

  • path string an absolute URL or a path relative to options.url.

Returns string the resolved, absolute URL.

Settles after an interaction (click, key press, etc.) before the next step runs, using the listener _armActionSettle started before the interaction was dispatched (armed; a fresh one is armed here too, as a safety net, if a call site forgot to — but arming this late can only miss a navigation that already started during the action’s own dispatch, exactly the race this design exists to avoid, so every call site should pass its own pre-armed armed, not rely on this fallback).

If options.waitForAction was set explicitly in the config, honors it literally as a fixed pacing sleep, exactly as before this round — an explicit value is a deliberate choice (slow-motion debugging, a known-slow app) this never second-guesses.

Otherwise, event-aware: races the armed listener against a fresh ACTION_SETTLE_GRACE_MS window (started now, not when it was armed — the action’s own dispatch already ran concurrently with the arm, so this is genuinely bounded extra time, not a guess). If nothing declares a navigation, returns immediately once the window elapses — the common case for most actions (typing, toggling a checkbox, focusing a field) — instead of a fixed options.waitForAction (100ms by default) sleep on every single action regardless of whether anything is happening.

If a navigation did start, _lastMainFrameNav (see _ensureLifecycleListener) is checked first: on a fast/local page, the entire lifecycle sequence through the target event has typically already arrived in the same batch that announced the navigation started, in which case this returns immediately. Only a navigation still genuinely in flight falls through to _waitForPageLoad (the same mechanism amOnPage/refreshPage use) — which waits for it to actually finish, rather than a fixed sleep that has no relationship to how long the navigation actually takes: strictly more correct for a slow navigation, not just faster for a fast one.

  • armed ({promise: Promise<(string | null)>, cancel: function} | null)? from _armActionSettle, called before the action.

Returns Promise

Starts waiting for a Page.lifecycleEvent named eventName for the given loaderId on the current session. loaderId (from the Page.navigate response) discriminates the awaited navigation from any other in-flight or stale lifecycle events (e.g. the about:blank target created in _before), which is essential since Chrome emits the target’s initial about:blank lifecycle sequence asynchronously, sometimes after this listener is already installed.

Returns a {promise, cancel} pair rather than a bare promise: _waitForPageLoad races this against a readyState poll, and whichever side loses must be actively torn down (not just have its rejection swallowed) — an abandoned-but-still-pending wait would sit in _pageLoadWaiters for the full timeout on every single navigation, for no purpose.

  • loaderId string the loader id of the navigation to wait for, from Page.navigate’s response.
  • eventName string the Page.lifecycleEvent name to wait for (e.g. load, DOMContentLoaded, networkIdle).
  • timeoutSec number maximum time to wait, in seconds.

Returns {promise: Promise, cancel: function}

Waits for a page to finish loading after Page.navigate/Page.reload, per options.waitForNavigation.

Purely event-driven for the first PAGE_LOAD_GRACE_MS: only the push-based Page.lifecycleEvent signal (matched by loaderId) is awaited, issuing zero _evaluate calls — this matters because an _evaluate sent while the page’s own JavaScript is still busy (e.g. a real-world page doing post-load hydration/analytics work) can queue behind it for hundreds of ms to multiple seconds, measured directly against a JS-heavy page. Only if the grace window elapses without the event (an engine that doesn’t emit it, or a genuinely slow navigation) does the document.readyState poll (via _poll) start, racing the still-pending lifecycle wait — both bounded by the same options.getPageTimeout, so a lifecycle-less engine costs at most PAGE_LOAD_GRACE_MS more than the poll alone would have, never double the timeout. No loaderId (e.g. from Page.reload, which returns none) skips straight to the poll.

Whichever side ultimately loses is actively cancelled, not merely abandoned — an abandoned poll or lifecycle wait would otherwise keep running (issuing readyState _evaluate calls every pollInterval, or holding a _pageLoadWaiters entry) for up to the full timeout on every navigation, competing for the same CDP connection with real work.

  • loaderId (string | null) loader id from the triggering Page.navigate response, if any.
  • timeoutMessage string error message used if the readyState poll times out.

Returns Promise

Starts a within block, scoping every subsequent _run call (and therefore every element lookup performed by this helper) to the descendants of the element matched by locator. Verifies the element exists (against the full document, i.e. unscoped) before narrowing.

  • locator (string | object) element located by CSS|XPath|strict locator.
  • Throws ElementNotFound if no element matches locator.

Returns Promise

Ends the current within block, restoring unscoped element lookups.

Returns Promise

Opens a web page in the current session.

I.amOnPage('/'); // opens main page of website
I.amOnPage('https://github.com'); // opens github
I.amOnPage('/login'); // opens a login page

Navigates via Page.navigate, then waits (up to options.getPageTimeout seconds) for the page to finish loading, preferring the push-based Page.lifecycleEvent signal (per options.waitForNavigation) over polling document.readyState. Capabilities are (re-)probed (a no-op after the first page, since they’re cached for the helper’s lifetime).

The in-page client is deliberately not eagerly (re-)installed here — navigation discards any previously injected script, but installing it is deferred to the first actual action after this call, via _runSelected’s sentinel-and-retry. This keeps amOnPage itself down to the navigate command plus the push-based wait: no _evaluate call is issued on this hot path, which matters most right when the page’s own JavaScript may still be busy (measured directly: an _evaluate sent in that window can queue behind it for hundreds of ms to multiple seconds on a JS-heavy real-world page, regardless of how small the evaluated expression is).

  • url string url path or global url.

Returns Promise

Appends text to a input field or textarea. Field is located by name, label, CSS or XPath

I.appendField('#myTextField', 'appended');
// typing secret
I.appendField('password', secret('123456'));
  • field (string | object) located by label|name|CSS|XPath|strict locator
  • value string text value to append.
  • context (string? | object) (optional, null by default) element to search in CSS|XPath|Strict locator.

Returns Promise

Attaches a file to a file input field, or drops it onto a drag-and-drop dropzone element, resolved by label|name|CSS|XPath|strict locator. pathToFile is resolved relative to codecept_dir (matching Puppeteer/WebDriver). Since CDPBrowser never brings element handles back to Node, the resolved element is marked with a throwaway data-codecept-upload attribute in-page (respecting context/within/elementIndex exactly like every other action). A real <input type="file"> is then addressed by that attribute through the CDP DOM domain, which CDPBrowser otherwise never uses, to call DOM.setFileInputFiles; any other element (a drag-and-drop dropzone) instead gets a synthetic dragenter/dragover/drop sequence with a DataTransfer built from the file’s contents, entirely in-page. The marker is removed again in a finally.

I.attachFile('Avatar', 'data/avatar.jpg');
I.attachFile('#file', 'data/avatar.jpg');
I.attachFile('#dropzone', 'data/avatar.jpg');
  • field (string | object) located by label|name|CSS|XPath|strict locator.
  • pathToFile string path to file, relative to codecept_dir.
  • context (string? | object) (optional, null by default) element to search in CSS|XPath|Strict locator.

Returns Promise

Removes focus from a given element.

I.blur('#name');
  • locator (string | object) element located by CSS|XPath|strict locator.

Returns Promise

Selects a checkbox or radio button. Element is located by label or name or CSS or XPath.

I.checkOption('#agree');
I.checkOption('I Agree to Terms and Conditions');
I.checkOption('agree', '//form');
  • field (string | object) checkbox located by label | name | CSS | XPath | strict locator.
  • context (string? | object) (optional, null by default) element located by CSS | XPath | strict locator.

Returns Promise

Clears the system clipboard.

I.clearClipboard();
I.seeClipboardEquals('');

Returns Promise

Clears a cookie by name, if none provided clears all cookies.

I.clearCookie();
I.clearCookie('test');
  • name (string | null) (optional, null by default) cookie name

Returns Promise

Clears a <textarea> or text <input> element’s value.

I.clearField('Email');
I.clearField('user[email]');
I.clearField('#email');
  • field (string | object) editable field located by label|name|CSS|XPath|strict locator.
  • context (string? | object) (optional, null by default) element to search in CSS|XPath|Strict locator.

Returns Promise

Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.

When options.input is 'cdp', the click is dispatched as real Input.dispatchMouseEvent mouse events (mouseMoved / mousePressed / mouseReleased) at the center of the element’s bounding box, so it exercises the same input pipeline a real user would. Otherwise it delegates to forceClick. A matched element with a zero-size bounding box (e.g. display: none) has no valid coordinate to click and throws; use forceClick to dispatch a synthetic click on such elements instead.

// simple link
I.click('Logout');
// button of form
I.click('Submit');
// CSS button
I.click('#form input[type=submit]');
// XPath
I.click('//form/*[@type=submit]');
// using strict locator
I.click({css: 'nav a.login'});
  • locator (string | object) clickable link or button located by text, or any element located by CSS|XPath|strict locator.
  • context (string? | object) (optional, null by default) element to search in CSS|XPath|Strict locator.
  • Throws Error if the matched element has a zero-size bounding box.

Returns Promise

Clicks at global page coordinates, or at coordinates relative to an element. Dispatches a real CDP mouse click and therefore requires a real layout engine.

I.clickXY(100, 200); // global coordinates
I.clickXY('#area', 50, 30); // relative to #area
  • locator (string | object | number) element to click relative to, or a global X coordinate.
  • x number? X coordinate relative to element, or global Y coordinate if locator is a number.
  • y number? Y coordinate relative to element.

Returns Promise

Opposite to see. Checks that a text is not present on a page. Use context parameter to narrow down the search.

I.dontSee('Login'); // assume we are already logged in.
I.dontSee('Login', '.nav'); // no login inside .nav element
  • text string which is not present.
  • context (string? | object) (optional) element located by CSS|XPath|strict locator in which to perform search.

Returns Promise

Verifies that the specified checkbox is not checked.

I.dontSeeCheckboxIsChecked('#agree'); // located by ID
I.dontSeeCheckboxIsChecked('I agree to terms'); // located by label
  • locator (string | object) located by label|name|CSS|XPath|strict locator.

Returns Promise

Checks that a cookie with the given name is not set.

Returns Promise

Opposite to seeCurrentPathEquals.

Returns Promise

Checks that current url is not equal to provided one. Unlike dontSeeInCurrentUrl performs a strict comparison.

Returns Promise

Opposite to seeElement. Checks that element is not visible.

I.dontSeeElement('.modal'); // modal is not shown
  • locator (string | object) located by CSS|XPath|strict locator.
  • context (string? | object) (optional, null by default) element to search in CSS|XPath|Strict locator.

Returns Promise

Opposite to seeElementInDOM. Checks that element is not on page.

I.dontSeeElementInDOM('.nav'); // checks that element is not on page visible or not
  • locator (string | object) located by CSS|XPath|strict locator.

Returns Promise

Checks that current url does not contain a provided fragment.

Returns Promise

Opposite to seeInField.

  • field (string | object) located by label|name|CSS|XPath|strict locator.
  • value (string | object) value to check.
  • context (string? | object) (optional, null by default) element to search in CSS|XPath|Strict locator.

Returns Promise

Checks that the current page does not contain the given string in its raw source code.

Returns Promise

Checks that title does not contain text.

Returns Promise

Verifies that a certain request is not part of network traffic.

Examples:

I.dontSeeTraffic({ name: 'Unexpected API Call', url: 'https://api.example.com' });
I.dontSeeTraffic({ name: 'Unexpected API Call of "user" endpoint', url: /api.example.com.*user/ });
  • opts Object options when checking the traffic network.

    • opts.name string A name of that request. Can be any value. Only relevant to have a more meaningful error message in case of fail.
    • opts.url (string | RegExp) Expected URL of request in network traffic. Can be a string or a regular expression.

Returns void automatically synchronized promise through #recorder

Performs a double-click on an element matched by locator.

I.doubleClick('Edit');
  • locator (string | object) clickable element located by text, or any element located by CSS|XPath|strict locator.
  • context (string? | object) (optional, null by default, currently ignored by this helper).

Returns Promise

Executes an asynchronous script (callback-style, in the same way window.setTimeout works) in the browser context and returns the value passed to done.

const val = await I.executeAsyncScript(function(val, done) {
setTimeout(() => done(val + 1), 100)
}, 5)
  • fn function an asynchronous function to be executed in the browser context; its last argument is a done callback.
  • args …any arguments to pass into the function (before done).

Returns Promise the value passed to done.

Executes a JavaScript function in the browser context and returns its result.

If a function is passed, it is serialized with Function.prototype.toString(), so it must not reference variables from the outer (Node.js) scope — pass any needed data as arguments instead. A string is evaluated as-is.

let title = await I.executeScript(() => document.title);
let sum = await I.executeScript((a, b) => a + b, 2, 3);

If the function returns a promise, executeScript waits for it to resolve.

  • fn (string | function) a JavaScript function to be executed in the browser context, or a string expression.
  • args …any arguments to pass into the function.

Returns Promise the value returned (or resolved) by the function.

Fills a text field or textarea, after clearing its value, with the given string. Field is located by name, label, CSS, or XPath.

// by label
I.fillField('Email', 'hello@world.com');
// by name
I.fillField('password', secret('123456'));
// by CSS
I.fillField('form#login input[name=username]', 'John');
// or by strict locator
I.fillField({css: 'form#login input[name=username]'}, 'John');
  • field (string | object) located by label|name|CSS|XPath|strict locator.
  • value (string | object) text value to fill.
  • context (string? | object) (optional, null by default) element to search in CSS|XPath|Strict locator.

Returns Promise

Resets all recorded network requests.

I.flushNetworkTraffics();

Focuses a given element.

I.focus('#name');
  • locator (string | object) element located by CSS|XPath|strict locator.

Returns Promise

Perform an emulated click on a link or a button, given by a locator. Unlike click, this always dispatches a synthetic in-page el.click() instead of sending native CDP input events. This works on hidden, animated or inactive elements as well.

If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the “value” attribute, “name” attribute, and inner text are searched. For links, the link text is searched. For images, the “alt” attribute and inner text of any parent links are searched.

// simple link
I.forceClick('Logout');
// button of form
I.forceClick('Submit');
// CSS button
I.forceClick('#form input[type=submit]');
// XPath
I.forceClick('//form/*[@type=submit]');
// using strict locator
I.forceClick({css: 'nav a.login'});
  • locator (string | object) clickable link or button located by text, or any element located by CSS|XPath|strict locator.
  • context (string? | object) (optional, null by default) element to search in CSS|XPath|Strict locator.

Returns Promise

Retrieves an attribute from an element located by CSS or XPath and returns it to test. Resumes test execution, so should be used inside async with await operator. If more than one element is found - attribute of first element is returned.

let hint = await I.grabAttributeFrom('#tooltip', 'title');
  • locator (string | object) element located by CSS|XPath|strict locator.
  • attr string attribute name.

Returns Promise<string> attribute value

Retrieves an array of attributes from elements located by CSS or XPath and returns it to test. Resumes test execution, so should be used inside async with await operator.

let hints = await I.grabAttributeFromAll('.tooltip', 'title');
  • locator (string | object) element located by CSS|XPath|strict locator.
  • attr string attribute name.

Returns Promise<Array<string>> array of attribute values

Gets a cookie object by name. If none provided gets all cookies. Resumes test execution, so should be used inside async function with await operator.

let cookie = await I.grabCookie('auth');
assert(cookie.value, '123456');
  • name (string | null) cookie name.

Returns Promise<(CodeceptJS.Cookie | Array<CodeceptJS.Cookie>)> a cookie object, or an array of all cookies when name is not provided.

Retrieves all cookies visible to the current page. Resumes test execution, so should be used inside async function with await operator.

let cookies = await I.grabCookies();

Returns Promise<Array<CodeceptJS.Cookie>> array of cookie objects.

Retrieves a CSS property from an element located by CSS or XPath. If more than one element is found - value of first element is returned.

const value = await I.grabCssPropertyFrom('h3', 'font-weight');
  • locator (string | object) element located by CSS|XPath|strict locator.
  • cssProperty string CSS property name.

Returns Promise<string> CSS value

Retrieves an array of CSS properties from elements located by CSS or XPath.

const values = await I.grabCssPropertyFromAll('h3', 'font-weight');
  • locator (string | object) element located by CSS|XPath|strict locator.
  • cssProperty string CSS property name.

Returns Promise<Array<string>> array of CSS values

Retrieves the page URL of the current page.

let url = await I.grabCurrentUrl();
console.log(`Current URL is [${url}]`);

Returns Promise<string> current URL.

Grabs the text content of the system clipboard. Resumes test execution, so should be used inside async function with await operator.

I.click('Copy to clipboard');
const url = await I.grabFromClipboard();

Returns Promise<string> the system clipboard contents.

Retrieves the inner HTML from an element located by CSS or XPath. If more than one element is found - HTML of first element is returned.

let postHTML = await I.grabHTMLFrom('#post');
  • locator (string | object) element located by CSS|XPath|strict locator.

Returns Promise<string> HTML code for an element

Retrieves the inner HTML from elements located by CSS or XPath.

let postHTMLs = await I.grabHTMLFromAll('.post');
  • locator (string | object) element located by CSS|XPath|strict locator.

Returns Promise<Array<string>> HTML code for matched elements

Grab number of elements by locator. Resumes test execution, so should be used inside async function with await operator.

let numOfElements = await I.grabNumberOfElements('p');
  • locator (string | object) located by CSS|XPath|strict locator.

Returns Promise<number> number of matched elements.

Grab number of visible elements by locator.

let numOfVisibleElements = await I.grabNumberOfVisibleElements('p');
  • locator (string | object) located by CSS|XPath|strict locator.

Returns Promise<number> number of visible matched elements.

Retrieves the current page scroll position.

let { x, y } = await I.grabPageScrollPosition();

Returns Promise<{x: number, y: number}> scroll position.

Grab the recording network traffics

const traffics = await I.grabRecordedNetworkTraffics();
expect(traffics[0].url).to.equal('https://reqres.in/api/comments/1');
expect(traffics[0].response.status).to.equal(200);
expect(traffics[0].response.body).to.contain({ name: 'this was mocked' });

Returns Array recorded network traffics

Retrieves the source code of the current page.

let pageSource = await I.grabSource();

Returns Promise<string> source code of the current page (the outer HTML of <html>).

Retrieves a text from an element located by CSS or XPath and returns it to test. Resumes test execution, so should be used inside async with await operator.

let pin = await I.grabTextFrom('#pin');

If multiple elements found returns first element.

  • locator (string | object) element located by CSS|XPath|strict locator.

Returns Promise<string> text value

Retrieves all texts from elements located by CSS or XPath and returns it to test. Resumes test execution, so should be used inside async with await operator.

let pins = await I.grabTextFromAll('#pin li');
  • locator (string | object) element located by CSS|XPath|strict locator.

Returns Promise<Array<string>> array of text values

Retrieves a page title.

let title = await I.grabTitle();

Returns Promise<string> title of the page.

Retrieves a value from a form element located by CSS or XPath and returns it to test. Resumes test execution, so should be used inside async function with await operator. If more than one element is found - value of first element is returned.

let email = await I.grabValueFrom('input[name=email]');
  • locator (string | object) field located by label|name|CSS|XPath|strict locator.

Returns Promise<string> attribute value

Retrieves an array of values from fields located by CSS or XPath and returns it to test. Resumes test execution, so should be used inside async function with await operator.

let inputs = await I.grabValueFromAll('//form/input');
  • locator (string | object) field located by label|name|CSS|XPath|strict locator.

Returns Promise<Array<string>> array of attribute values

Retrieves the first WebElement matching a locator.

const button = await I.grabWebElement({ role: 'button', text: 'Submit' });
  • locator (string | object) element located by CSS|XPath|strict locator.
  • Throws ElementNotFound if no element matches locator.

Returns Promise<object> a WebElement instance.

Retrieves an array of WebElements matching a locator (lib/element/WebElement.js, wrapping a CDPElementHandle). Element handles are re-resolved on demand by re-running candidates and picking the matching index, since CDPBrowser never keeps a persistent handle to a DOM node on the Node side.

const buttons = await I.grabWebElements({ role: 'button' });
  • locator (string | object) element located by CSS|XPath|strict locator.

Returns Promise<Array<object>> array of WebElement instances.

Presses a key or key combination on the currently focused element. Under options.strict, a modifier+editing-key combination (e.g. Ctrl+A) dispatched with no element focused throws NonFocusedType, mirroring focusCheck.js’s behavior on other helpers.

I.pressKey('Enter');
I.pressKey(['Control', 'a']);
  • key (string | Array<string>) a key or an array of keys to combine (modifiers first).

Returns Promise

Reloads the current page.

I.refreshPage();

Triggers Page.reload and waits (up to options.getPageTimeout seconds) for document.readyState to reach 'complete'.

Returns Promise

Resizes the browser viewport.

I.resizeWindow(1024, 768);
  • width (number | "maximize") window width, or 'maximize'.
  • height number? window height.

Returns Promise

Performs a right-click on an element matched by locator.

I.rightClick('Menu');
  • locator (string | object) clickable element located by text, or any element located by CSS|XPath|strict locator.
  • context (string? | object) (optional, null by default, currently ignored by this helper).

Returns Promise

Saves a screenshot of a single element to the output folder.

I.saveElementScreenshot('#logo', 'logo.png');
  • locator (string | object) element located by CSS|XPath|strict locator.
  • fileName string file name to save.

Returns Promise

Saves a screenshot to the output folder (set in codecept.conf.ts or codecept.conf.js). Filename is relative to the output folder.

I.saveScreenshot('debug.png');
  • fileName string file name to save.

Returns Promise

Scrolls to the bottom of the page.

I.scrollPageToBottom();

Returns Promise

Scrolls to the top of the page.

I.scrollPageToTop();

Returns Promise

Scrolls to the element matched by locator, or to given coordinates.

I.scrollTo('#submit');
I.scrollTo(100, 200);
  • locator (string | object | number) element to scroll to, or an X coordinate if no element.
  • offsetX number X offset, or Y coordinate if locator is a number.
  • offsetY number Y offset applied when scrolling to an element.

Returns Promise

Checks that a page contains a visible text. Use context parameter to narrow down the search.

I.see('Welcome'); // text welcome on a page
I.see('Welcome', '.content'); // text inside .content div
I.see('Register', {css: 'form.register'}); // use strict locator
  • text string expected on page.
  • context (string? | object) (optional, null by default) element located by CSS|Xpath|strict locator in which to search for text.

Returns Promise

Checks that all elements matched by locator have the given attribute values. An expected value is matched either as an exact match or as a regular expression against the actual value.

I.seeAttributesOnElements('//form', { method: 'post' });
  • locator (string | object) element located by CSS|XPath|strict locator.
  • attributes object object with attribute names and expected values.

Returns Promise

Verifies that the specified checkbox is checked.

I.seeCheckboxIsChecked('Agree');
I.seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
I.seeCheckboxIsChecked({css: '#signup_form input[type=checkbox]'});
  • locator (string | object) located by label|name|CSS|XPath|strict locator.

Returns Promise

Checks that the system clipboard is equal to the given text.

I.click('Copy to clipboard');
I.seeClipboardEquals('https://codecept.io');

Reading the clipboard requires a secure context (https or localhost).

Returns Promise

Checks that a cookie with the given name is set.

Returns Promise

Checks that all elements matched by locator have the given CSS properties.

I.seeCssPropertiesOnElements('h3', { 'font-weight': 'bold', display: 'block' });
  • locator (string | object) element located by CSS|XPath|strict locator.
  • cssProperties object object with CSS properties and their values to check.

Returns Promise

Checks that current url path (ignoring query string and hash) equals to provided one.

I.seeCurrentPathEquals('/info');

Returns Promise

Checks that current url is equal to provided one. Unlike seeInCurrentUrl performs a strict comparison.

I.seeCurrentUrlEquals('/register');

Returns Promise

Checks that a given Element is visible. Element is located by CSS or XPath.

I.seeElement('#modal');
  • locator (string | object) located by CSS|XPath|strict locator.
  • context (string? | object) (optional, null by default) element to search in CSS|XPath|Strict locator.

Returns Promise

Checks that a given Element is present in the DOM. Element is located by CSS or XPath.

I.seeElementInDOM('#modal');
  • locator (string | object) element located by CSS|XPath|strict locator.

Returns Promise

Checks that the system clipboard contains the given text.

I.click('Copy to clipboard');
I.seeInClipboard('https://codecept.io');

Reading the clipboard requires a secure context (https or localhost).

Returns Promise

Checks that current url contains a provided fragment.

I.seeInCurrentUrl('/register'); // we are on registration page
  • url string a fragment to check

Returns Promise

Checks that the given input field or textarea equals (contains) the given value. For fuzzy locators, the field is searched by label|name|CSS|XPath|strict locator.

I.seeInField('Username', 'davert');
  • field (string | object) located by label|name|CSS|XPath|strict locator.
  • value (string | object) value to check.
  • context (string? | object) (optional, null by default) element to search in CSS|XPath|Strict locator.

Returns Promise

Checks that the current page contains the given string in its raw source code.

I.seeInSource('<h1>Green eggs &amp; ham</h1>');

Returns Promise

Checks that title contains text.

I.seeInTitle('Home Page');
  • text string text value to check.

Returns Promise

Asserts that an element appears a given number of times on the page, and that all matching elements are visible.

I.seeNumberOfVisibleElements('.buttons', 3);
  • locator (string | object) located by CSS|XPath|strict locator.
  • num number expected number of elements.

Returns Promise

Verifies that a certain request is part of network traffic.

// checking the request url contains certain query strings
I.amOnPage('https://openai.com/blog/chatgpt');
I.startRecordingTraffic();
await I.seeTraffic({
name: 'sentry event',
url: 'https://images.openai.com/blob/cf717bdb-0c8c-428a-b82b-3c3add87a600',
parameters: {
width: '1919',
height: '1138',
},
});
// checking the request url contains certain post data
I.amOnPage('https://openai.com/blog/chatgpt');
I.startRecordingTraffic();
await I.seeTraffic({
name: 'event',
url: 'https://cloudflareinsights.com/cdn-cgi/rum',
requestPostData: {
st: 2,
},
});
  • opts Object options when checking the traffic network.

    • opts.name string A name of that request. Can be any value. Only relevant to have a more meaningful error message in case of fail.
    • opts.url string Expected URL of request in network traffic
    • opts.parameters Object? Expected parameters of that request in network traffic
    • opts.requestPostData Object? Expected that request contains post data in network traffic
    • opts.timeout number? Timeout to wait for request in seconds. Default is 10 seconds.

Returns void automatically synchronized promise through #recorder

Selects an option in a drop-down select. Field is searched by label | name | CSS | XPath. Option is selected by visible text or by value.

I.selectOption('Choose Plan', 'Monthly'); // select by label
I.selectOption('subscription', 'Monthly'); // match option by text
I.selectOption('subscription', '0'); // or by value
I.selectOption('//form/select[@name=account]','Premium');
I.selectOption('form select[name=account]', 'Premium');
I.selectOption({css: 'form select[name=account]'}, 'Premium');
  • select (string | object) field located by label|name|CSS|XPath|strict locator.
  • option (string | Array<string>) visible text or value of option, or an array of them for a multi-select.
  • context (string? | object) (optional, null by default) element to search in CSS|XPath|Strict locator.

Returns Promise

Sets cookie(s).

Can be a single cookie object or an array of cookies:

I.setCookie({name: 'auth', value: true});
// as array
I.setCookie([
{name: 'auth', value: true},
{name: 'agree', value: true}
]);
  • cookie (CodeceptJS.Cookie | Array<CodeceptJS.Cookie>) a cookie object or array of cookie objects.

Returns Promise

Starts recording network traffic via CDP’s Network.requestWillBeSent/responseReceived events, in the same shape ({url, method, requestHeaders, requestPostData, response} per request, response a promise of {url(), status(), statusText(), body()}) the shared lib/helper/network actions expect from Puppeteer/Playwright. The CDP listeners are installed once (lazily) and left in place afterwards, since CDPConnection has no listener removal and this.cdp is reused across tests; they filter by this.sessionId, so only the currently active test/page’s requests are recorded.

I.startRecordingTraffic();

Returns Promise

Starts recording a CDP Page.startScreencast session for the current test’s target: frames arrive as Page.screencastFrame events, are acknowledged immediately (Page.screencastFrameAck, required or the browser stops sending more), and buffered in this._screencastFrames. The underlying Page.screencastFrame listener is installed once (lazily) and left in place, like startRecordingTraffic’s listeners, since CDPConnection has no listener-removal API; it filters by this.sessionId so only the currently active test’s frames are buffered. Call stopScreencast to end the capture and assemble the buffered frames into an APNG.

I.startScreencast();
  • options object? {maxWidth: number, maxHeight: number, quality: number, everyNthFrame: number} — CDP Page.startScreencast pass-throughs. format is always 'png'.

Returns Promise

Stops recording network traffic started by startRecordingTraffic. Already-recorded requests in this.requests are kept; only new requests stop being appended.

I.stopRecordingTraffic();

Returns void

Stops the screencast started by startScreencast and assembles the buffered frames into a single APNG (Animated PNG) file, returned as a Buffer. Frame delays are derived from the CDP frame metadata’s timestamp deltas (frame arrival is activity-driven — Obscura and Chrome both only emit a frame on damage — so this reproduces the actual pacing of what happened, not a fixed frame rate); the last frame is held for options.lastFrameDelayMs (default 1000ms) since it has no “next” frame to derive a delay from. Every frame is checked for the PNG signature before assembly — CDP’s format: 'png' is honored by both Chrome and Obscura (verified directly), but if some other engine ever sends a different format regardless, this reports it via debugSection and returns null instead of muxing a broken file. Returns null if no frames were captured (screencast never started, or stopped immediately after starting).

const apngBuffer = await I.stopScreencast();
  • options object? {lastFrameDelayMs: number} — hold time in milliseconds for the final frame (default 1000).

Returns Promise<object> a Buffer with the assembled APNG, or null if there was nothing to assemble.

Types characters into the currently focused element (as set by click, focus, etc). Each character dispatches a real keydownkeypress → (value mutated) → inputkeyup sequence, and mutates a contenteditable host’s textContent instead of .value, so this works on rich-text/contenteditable targets as well as input/textarea. Mirrors Puppeteer’s type(text, options) semantics.

Without a delay, every character is dispatched in a single round-trip to the page. With a delay, characters are dispatched one round-trip at a time so the requested pause actually elapses between key presses.

I.click('Name');
I.type('CodeceptJS');
I.type(['C', 'o', 'd', 'e']);
  • keys (string | Array<string>) characters to type, either as a string or an array of characters.
  • delay number? (optional) delay in milliseconds between key presses.

Returns Promise

Unselects a checkbox or radio button. Element is located by label or name or CSS or XPath.

I.uncheckOption('#agree');
I.uncheckOption('I Agree to Terms and Conditions');
I.uncheckOption('agree', '//form');
  • field (string | object) checkbox located by label | name | CSS | XPath | strict locator.
  • context (string? | object) (optional, null by default) element located by CSS | XPath | strict locator.

Returns Promise

Pauses execution for a number of seconds.

I.wait(2); // waits 2 secs
  • sec number number of seconds to wait.

Returns Promise

Waits for current url path (ignoring query string and hash) to equal to the expected.

I.waitCurrentPathEquals('/info', 2);
  • path string value to check.
  • sec number? (optional, options.waitForTimeout by default) time in seconds to wait

Returns Promise

Waits for a cookie with the given name to be set (by default waits for options.waitForTimeout seconds).

I.waitForCookie('auth', 5);
  • name string cookie name.
  • sec number? (optional, options.waitForTimeout by default) time in seconds to wait

Returns Promise

Waits for an element to be removed from the DOM (by default waits for options.waitForTimeout seconds).

I.waitForDetached('#popup', 5);
  • locator (string | object) element located by CSS|XPath|strict locator.
  • sec number? (optional, options.waitForTimeout by default) time in seconds to wait

Returns Promise

Waits for element to be present on page (by default waits for options.waitForTimeout seconds). Element can be located by CSS or XPath.

I.waitForElement('.btn.continue');
I.waitForElement('.btn.continue', 5); // wait for 5 secs
  • locator (string | object) element located by CSS|XPath|strict locator.
  • sec number? (optional, options.waitForTimeout by default) time in seconds to wait

Returns Promise

Waits for a function to return true (waits for options.waitForTimeout seconds by default). Running in browser context.

I.waitForFunction(() => window.requests == 0);
I.waitForFunction(() => window.requests == 0, 5); // waits for 5 sec
I.waitForFunction((count) => window.requests == count, [3], 5) // pass args and wait for 5 sec
  • fn (string | function) to be executed in browser context.
  • argsOrSec (Array | number)? (optional) arguments for function or, if a number, seconds to wait.
  • sec number? (optional, options.waitForTimeout by default) time in seconds to wait

Returns Promise

Waits for an element to become invisible (by default waits for options.waitForTimeout seconds).

I.waitForInvisible('#popup', 5);
  • locator (string | object) element located by CSS|XPath|strict locator.
  • sec number? (optional, options.waitForTimeout by default) time in seconds to wait

Returns Promise

Waits for a text to appear (by default waits for options.waitForTimeout seconds). Element can be located by CSS or XPath. Narrow down search results by providing context.

I.waitForText('Thank you, form has been submitted');
I.waitForText('Thank you, form has been submitted', 5, '#modal');
  • text string to wait for.
  • sec number? (optional, options.waitForTimeout by default) time in seconds to wait
  • context (string? | object) (optional) element located by CSS|XPath|strict locator.

Returns Promise

Waits for an element to become visible (by default waits for options.waitForTimeout seconds).

I.waitForVisible('#popup', 5);
  • locator (string | object) element located by CSS|XPath|strict locator.
  • sec number? (optional, options.waitForTimeout by default) time in seconds to wait

Returns Promise

Waiting for the part of the URL to match the expected. Useful for SPA to understand that page was changed.

I.waitInUrl('/info', 2);
  • urlPart string value to check.
  • sec number? (optional, options.waitForTimeout by default) time in seconds to wait

Returns Promise

Waits for an element to be hidden. Alias of waitForInvisible.

  • locator (string | object) element located by CSS|XPath|strict locator.
  • sec number? (optional, options.waitForTimeout by default) time in seconds to wait

Returns Promise

Waits for the entire URL to match the expected (by default waits for options.waitForTimeout seconds).

I.waitUrlEquals('/info', 2);
  • urlPart string value to check.
  • sec number? (optional, options.waitForTimeout by default) time in seconds to wait

Returns Promise