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.
Example
Section titled “Example”// inside codecept.conf.js{ helpers: { CDPBrowser: { url: 'http://localhost', endpoint: 'http://127.0.0.1:9222', } }}Configuration
Section titled “Configuration”This helper should be configured in codecept.conf.js
Type: object
Properties
Section titled “Properties”urlstring? base url of website to be tested.endpointstring? Chrome DevTools Protocol endpoint. Either anhttp(s)://address exposing/json/version(from which thewebSocketDebuggerUrlis resolved) or a rawws(s)://debugger URL.headersobject? headers sent with the endpoint resolution request and the WebSocket handshake. Useful for authenticated remote browser providers.inputstring? how synthetic user actions (click, fill, etc.) are dispatched by helpers built on top of this class.autopickscdpwhen a real layout engine is detected andsyntheticotherwise; can be pinned tocdporsynthetic.xpathPolyfill(string | boolean)? whether to inject the bundled XPath polyfill before installing the in-page client.autoprobes the page and only injects whendocument.evaluateis unavailable or broken;true/falseforce the behavior.capabilitiesobject? pre-seed detected browser capabilities (layout,xpath,screenshot,innerText) to skip runtime probing. Values set here are never overwritten by_probeCapabilities/_ensureClient.waitForTimeoutnumber? default wait* timeout in seconds, used by helpers built on top of this class.waitForActionnumber? 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.pollIntervalnumber? interval in milliseconds between retries while polling for a condition (e.g. page ready state,waitFor*). Distinct fromwaitForAction.getPageTimeoutnumber? 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).waitForNavigationstring? when to consider a navigation finished:load,domcontentloaded, ornetworkidle. Mirrors the Puppeteer helper’s option name.networkidlewaits for the CDPnetworkIdlelifecycle event, which on a busy page can lagloadby a second or more — only opt in if the extra wait is actually needed.
Methods
Section titled “Methods”Parameters
Section titled “Parameters”configCDPBrowserConfig
_after
Section titled “_after”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.
_armActionSettle
Section titled “_armActionSettle”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)
_assertLayoutSupported
Section titled “_assertLayoutSupported”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.
Parameters
Section titled “Parameters”actionstring name of the calling assertion, used in the error message.
- Throws Error if the page has no layout engine.
_before
Section titled “_before”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.
_candidates
Section titled “_candidates”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.
Parameters
Section titled “Parameters”locator(string | object) element located by CSS|XPath|strict locator, or plain fuzzy text.kind("element"|"clickable"|"field"|"checkable") matching strategy to use whenlocatoris fuzzy.
_candidatesLabel
Section titled “_candidatesLabel”A short, human-readable label built from candidates, used in _run’s elementIndex/strict
error messages when no locator string is otherwise available.
Parameters
Section titled “Parameters”candidates
Returns string
_candidatesNeedXPath
Section titled “_candidatesNeedXPath”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.
Parameters
Section titled “Parameters”Returns boolean
_checkText
Section titled “_checkText”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.
Parameters
Section titled “Parameters”Returns Promise
_connect
Section titled “_connect”Resolves the CDP endpoint and opens the underlying CDPConnection, storing it on this.cdp.
_ensureClient
Section titled “_ensureClient”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.
_ensureLifecycleListener
Section titled “_ensureLifecycleListener”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 wheneverloaderIdchanges). On a fast/local navigation, the same raw probe found the entire sequence —initthroughnetworkIdle— arriving as one batch while the triggering action’s own round trip was still in flight. Without this cache,_waitForActionwould correctly detect that a navigation started, then arm a fresh wait for theloadevent specifically — which, in that common case, had already fired and will never fire again, paying the full grace-window-plus-poll cost of_waitForPageLoadon every single navigating action instead of settling immediately.
_evaluate
Section titled “_evaluate”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.
Parameters
Section titled “Parameters”expressionstring a JavaScript expression (or IIFE) to run in the page context.
Returns Promiseundefined if the expression has no result.
_finishTest
Section titled “_finishTest”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.
_grabCurrentPath
Section titled “_grabCurrentPath”Resolves the current page URL to a pathname, ignoring the origin, query string, and hash.
Returns Promise<string> the pathname of the current page.
_grantClipboardAccess
Section titled “_grantClipboardAccess”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.
_installClient
Section titled “_installClient”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.
Parameters
Section titled “Parameters”needsXPathboolean
_needsVisibleTextFallback
Section titled “_needsVisibleTextFallback”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.
_needsXPathPolyfill
Section titled “_needsXPathPolyfill”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.
_onScreencastFrame
Section titled “_onScreencastFrame”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.
Parameters
Section titled “Parameters”paramssessionId
_onTrafficLoadingFailed
Section titled “_onTrafficLoadingFailed”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.
Parameters
Section titled “Parameters”paramssessionId
_onTrafficRequest
Section titled “_onTrafficRequest”Network.requestWillBeSent handler, pushed into this.requests when it belongs to the
currently active session and recording is on.
Parameters
Section titled “Parameters”paramssessionId
_onTrafficResponse
Section titled “_onTrafficResponse”Network.responseReceived handler, resolving the matching pending response promise pushed
by _onTrafficRequest with a Puppeteer-HTTPResponse-like object.
Parameters
Section titled “Parameters”paramssessionId
Repeatedly calls fn until it returns a truthy value or timeoutSec elapses, checking
immediately and waiting options.pollInterval milliseconds between subsequent attempts.
Parameters
Section titled “Parameters”fnfunction the condition to poll; should resolve to a truthy value once satisfied.timeoutSecnumber maximum time to poll, in seconds.messagestring error message used when the timeout is reached.cancelToken{cancelled: boolean}?? whencancelledbecomestrue(set by the caller from outside), polling stops early with an error instead of continuing totimeoutSec. Used by_waitForPageLoadto tear down the losing side of a race instead of leaving it running.
- Throws Error with
messageiftimeoutSecelapses withoutfnreturning a truthy value, or a cancellation error ifcancelToken.cancelledis set first.
Returns Promisefn.
_probeCapabilities
Section titled “_probeCapabilities”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.
_resolveEndpoint
Section titled “_resolveEndpoint”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.
Parameters
Section titled “Parameters”candidatesactionstring name of the action to run against the matched elements (e.g.count,click,fill).payloadobject? extra data the action needs (e.g.{ value }forfill).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.
_runSelected
Section titled “_runSelected”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.
Parameters
Section titled “Parameters”candidatesactionstringpayload(object | null)selection(object | null){index}or{strict: true}, mirroring_selectionDescriptor.context(string? | object)
Returns Promise<{found: number, result: any}>
_runTextCheck
Section titled “_runTextCheck”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.
Parameters
Section titled “Parameters”Returns Promise<{found: boolean, snippet: (string | null)}>
_seeInField
Section titled “_seeInField”Shared implementation for seeInField/dontSeeInField.
Parameters
Section titled “Parameters”assertType("assert"|"negate")field(string | object)value(string | object)context(string? | object)
Returns Promise
_selectionDescriptor
Section titled “_selectionDescriptor”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.
_texts
Section titled “_texts”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.
Parameters
Section titled “Parameters”Returns Promise<{found: number, result: any}>
_textSource
Section titled “_textSource”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.
Parameters
Section titled “Parameters”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.
Parameters
Section titled “Parameters”pathstring an absolute URL or a path relative tooptions.url.
Returns string the resolved, absolute URL.
_waitForAction
Section titled “_waitForAction”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.
Parameters
Section titled “Parameters”armed({promise: Promise<(string | null)>, cancel: function} | null)? from_armActionSettle, called before the action.
Returns Promise
_waitForLoadEvent
Section titled “_waitForLoadEvent”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.
Parameters
Section titled “Parameters”loaderIdstring the loader id of the navigation to wait for, fromPage.navigate’s response.eventNamestring thePage.lifecycleEventname to wait for (e.g.load,DOMContentLoaded,networkIdle).timeoutSecnumber maximum time to wait, in seconds.
Returns {promise: Promise
_waitForPageLoad
Section titled “_waitForPageLoad”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.
Parameters
Section titled “Parameters”loaderId(string | null) loader id from the triggeringPage.navigateresponse, if any.timeoutMessagestring error message used if the readyState poll times out.
Returns Promise
_withinBegin
Section titled “_withinBegin”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.
Parameters
Section titled “Parameters”- Throws ElementNotFound if no element matches
locator.
Returns Promise
_withinEnd
Section titled “_withinEnd”Ends the current within block, restoring unscoped element lookups.
Returns Promise
amOnPage
Section titled “amOnPage”Opens a web page in the current session.
I.amOnPage('/'); // opens main page of websiteI.amOnPage('https://github.com'); // opens githubI.amOnPage('/login'); // opens a login pageNavigates 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).
Parameters
Section titled “Parameters”urlstring url path or global url.
Returns Promise
appendField
Section titled “appendField”Appends text to a input field or textarea. Field is located by name, label, CSS or XPath
I.appendField('#myTextField', 'appended');// typing secretI.appendField('password', secret('123456'));Parameters
Section titled “Parameters”field(string | object) located by label|name|CSS|XPath|strict locatorvaluestring text value to append.context(string? | object) (optional,nullby default) element to search in CSS|XPath|Strict locator.
Returns Promise
attachFile
Section titled “attachFile”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');Parameters
Section titled “Parameters”field(string | object) located by label|name|CSS|XPath|strict locator.pathToFilestring path to file, relative tocodecept_dir.context(string? | object) (optional,nullby default) element to search in CSS|XPath|Strict locator.
Returns Promise
Removes focus from a given element.
I.blur('#name');Parameters
Section titled “Parameters”Returns Promise
checkOption
Section titled “checkOption”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');Parameters
Section titled “Parameters”field(string | object) checkbox located by label | name | CSS | XPath | strict locator.context(string? | object) (optional,nullby default) element located by CSS | XPath | strict locator.
Returns Promise
clearClipboard
Section titled “clearClipboard”Clears the system clipboard.
I.clearClipboard();I.seeClipboardEquals('');Returns Promise
clearCookie
Section titled “clearCookie”Clears a cookie by name, if none provided clears all cookies.
I.clearCookie();I.clearCookie('test');Parameters
Section titled “Parameters”name(string | null) (optional,nullby default) cookie name
Returns Promise
clearField
Section titled “clearField”Clears a <textarea> or text <input> element’s value.
I.clearField('Email');I.clearField('user[email]');I.clearField('#email');Parameters
Section titled “Parameters”field(string | object) editable field located by label|name|CSS|XPath|strict locator.context(string? | object) (optional,nullby 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 linkI.click('Logout');// button of formI.click('Submit');// CSS buttonI.click('#form input[type=submit]');// XPathI.click('//form/*[@type=submit]');// using strict locatorI.click({css: 'nav a.login'});Parameters
Section titled “Parameters”locator(string | object) clickable link or button located by text, or any element located by CSS|XPath|strict locator.context(string? | object) (optional,nullby default) element to search in CSS|XPath|Strict locator.
- Throws Error if the matched element has a zero-size bounding box.
Returns Promise
clickXY
Section titled “clickXY”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 coordinatesI.clickXY('#area', 50, 30); // relative to #areaParameters
Section titled “Parameters”locator(string | object | number) element to click relative to, or a global X coordinate.xnumber? X coordinate relative to element, or global Y coordinate iflocatoris a number.ynumber? Y coordinate relative to element.
Returns Promise
dontSee
Section titled “dontSee”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 elementParameters
Section titled “Parameters”textstring which is not present.context(string? | object) (optional) element located by CSS|XPath|strict locator in which to perform search.
Returns Promise
dontSeeCheckboxIsChecked
Section titled “dontSeeCheckboxIsChecked”Verifies that the specified checkbox is not checked.
I.dontSeeCheckboxIsChecked('#agree'); // located by IDI.dontSeeCheckboxIsChecked('I agree to terms'); // located by labelParameters
Section titled “Parameters”Returns Promise
dontSeeCookie
Section titled “dontSeeCookie”Checks that a cookie with the given name is not set.
Parameters
Section titled “Parameters”namestring cookie name.
Returns Promise
dontSeeCurrentPathEquals
Section titled “dontSeeCurrentPathEquals”Opposite to seeCurrentPathEquals.
Parameters
Section titled “Parameters”pathstring value to check.
Returns Promise
dontSeeCurrentUrlEquals
Section titled “dontSeeCurrentUrlEquals”Checks that current url is not equal to provided one.
Unlike dontSeeInCurrentUrl performs a strict comparison.
Parameters
Section titled “Parameters”urlstring value to check.
Returns Promise
dontSeeElement
Section titled “dontSeeElement”Opposite to seeElement. Checks that element is not visible.
I.dontSeeElement('.modal'); // modal is not shownParameters
Section titled “Parameters”locator(string | object) located by CSS|XPath|strict locator.context(string? | object) (optional,nullby default) element to search in CSS|XPath|Strict locator.
Returns Promise
dontSeeElementInDOM
Section titled “dontSeeElementInDOM”Opposite to seeElementInDOM. Checks that element is not on page.
I.dontSeeElementInDOM('.nav'); // checks that element is not on page visible or notParameters
Section titled “Parameters”Returns Promise
dontSeeInCurrentUrl
Section titled “dontSeeInCurrentUrl”Checks that current url does not contain a provided fragment.
Parameters
Section titled “Parameters”urlstring value to check.
Returns Promise
dontSeeInField
Section titled “dontSeeInField”Opposite to seeInField.
Parameters
Section titled “Parameters”field(string | object) located by label|name|CSS|XPath|strict locator.value(string | object) value to check.context(string? | object) (optional,nullby default) element to search in CSS|XPath|Strict locator.
Returns Promise
dontSeeInSource
Section titled “dontSeeInSource”Checks that the current page does not contain the given string in its raw source code.
Parameters
Section titled “Parameters”textstring value to check.
Returns Promise
dontSeeInTitle
Section titled “dontSeeInTitle”Checks that title does not contain text.
Parameters
Section titled “Parameters”textstring value to check.
Returns Promise
dontSeeTraffic
Section titled “dontSeeTraffic”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/ });Parameters
Section titled “Parameters”-
optsObject options when checking the traffic network.
Returns void automatically synchronized promise through #recorder
doubleClick
Section titled “doubleClick”Performs a double-click on an element matched by locator.
I.doubleClick('Edit');Parameters
Section titled “Parameters”locator(string | object) clickable element located by text, or any element located by CSS|XPath|strict locator.context(string? | object) (optional,nullby default, currently ignored by this helper).
Returns Promise
executeAsyncScript
Section titled “executeAsyncScript”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)Parameters
Section titled “Parameters”fnfunction an asynchronous function to be executed in the browser context; its last argument is adonecallback.args…any arguments to pass into the function (beforedone).
Returns Promisedone.
executeScript
Section titled “executeScript”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.
Parameters
Section titled “Parameters”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
fillField
Section titled “fillField”Fills a text field or textarea, after clearing its value, with the given string. Field is located by name, label, CSS, or XPath.
// by labelI.fillField('Email', 'hello@world.com');// by nameI.fillField('password', secret('123456'));// by CSSI.fillField('form#login input[name=username]', 'John');// or by strict locatorI.fillField({css: 'form#login input[name=username]'}, 'John');Parameters
Section titled “Parameters”field(string | object) located by label|name|CSS|XPath|strict locator.value(string | object) text value to fill.context(string? | object) (optional,nullby default) element to search in CSS|XPath|Strict locator.
Returns Promise
flushNetworkTraffics
Section titled “flushNetworkTraffics”Resets all recorded network requests.
I.flushNetworkTraffics();Focuses a given element.
I.focus('#name');Parameters
Section titled “Parameters”Returns Promise
forceClick
Section titled “forceClick”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 linkI.forceClick('Logout');// button of formI.forceClick('Submit');// CSS buttonI.forceClick('#form input[type=submit]');// XPathI.forceClick('//form/*[@type=submit]');// using strict locatorI.forceClick({css: 'nav a.login'});Parameters
Section titled “Parameters”locator(string | object) clickable link or button located by text, or any element located by CSS|XPath|strict locator.context(string? | object) (optional,nullby default) element to search in CSS|XPath|Strict locator.
Returns Promise
grabAttributeFrom
Section titled “grabAttributeFrom”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');Parameters
Section titled “Parameters”Returns Promise<string> attribute value
grabAttributeFromAll
Section titled “grabAttributeFromAll”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');Parameters
Section titled “Parameters”Returns Promise<Array<string>> array of attribute values
grabCookie
Section titled “grabCookie”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');Parameters
Section titled “Parameters”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.
grabCookies
Section titled “grabCookies”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.
grabCssPropertyFrom
Section titled “grabCssPropertyFrom”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');Parameters
Section titled “Parameters”locator(string | object) element located by CSS|XPath|strict locator.cssPropertystring CSS property name.
Returns Promise<string> CSS value
grabCssPropertyFromAll
Section titled “grabCssPropertyFromAll”Retrieves an array of CSS properties from elements located by CSS or XPath.
const values = await I.grabCssPropertyFromAll('h3', 'font-weight');Parameters
Section titled “Parameters”locator(string | object) element located by CSS|XPath|strict locator.cssPropertystring CSS property name.
Returns Promise<Array<string>> array of CSS values
grabCurrentUrl
Section titled “grabCurrentUrl”Retrieves the page URL of the current page.
let url = await I.grabCurrentUrl();console.log(`Current URL is [${url}]`);Returns Promise<string> current URL.
grabFromClipboard
Section titled “grabFromClipboard”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.
grabHTMLFrom
Section titled “grabHTMLFrom”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');Parameters
Section titled “Parameters”Returns Promise<string> HTML code for an element
grabHTMLFromAll
Section titled “grabHTMLFromAll”Retrieves the inner HTML from elements located by CSS or XPath.
let postHTMLs = await I.grabHTMLFromAll('.post');Parameters
Section titled “Parameters”Returns Promise<Array<string>> HTML code for matched elements
grabNumberOfElements
Section titled “grabNumberOfElements”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');Parameters
Section titled “Parameters”Returns Promise<number> number of matched elements.
grabNumberOfVisibleElements
Section titled “grabNumberOfVisibleElements”Grab number of visible elements by locator.
let numOfVisibleElements = await I.grabNumberOfVisibleElements('p');Parameters
Section titled “Parameters”Returns Promise<number> number of visible matched elements.
grabPageScrollPosition
Section titled “grabPageScrollPosition”Retrieves the current page scroll position.
let { x, y } = await I.grabPageScrollPosition();Returns Promise<{x: number, y: number}> scroll position.
grabRecordedNetworkTraffics
Section titled “grabRecordedNetworkTraffics”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
grabSource
Section titled “grabSource”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>).
grabTextFrom
Section titled “grabTextFrom”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.
Parameters
Section titled “Parameters”Returns Promise<string> text value
grabTextFromAll
Section titled “grabTextFromAll”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');Parameters
Section titled “Parameters”Returns Promise<Array<string>> array of text values
grabTitle
Section titled “grabTitle”Retrieves a page title.
let title = await I.grabTitle();Returns Promise<string> title of the page.
grabValueFrom
Section titled “grabValueFrom”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]');Parameters
Section titled “Parameters”Returns Promise<string> attribute value
grabValueFromAll
Section titled “grabValueFromAll”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');Parameters
Section titled “Parameters”Returns Promise<Array<string>> array of attribute values
grabWebElement
Section titled “grabWebElement”Retrieves the first WebElement matching a locator.
const button = await I.grabWebElement({ role: 'button', text: 'Submit' });Parameters
Section titled “Parameters”- Throws ElementNotFound if no element matches
locator.
Returns Promise<object> a WebElement instance.
grabWebElements
Section titled “grabWebElements”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' });Parameters
Section titled “Parameters”Returns Promise<Array<object>> array of WebElement instances.
pressKey
Section titled “pressKey”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']);Parameters
Section titled “Parameters”Returns Promise
refreshPage
Section titled “refreshPage”Reloads the current page.
I.refreshPage();Triggers Page.reload and waits (up to options.getPageTimeout seconds) for
document.readyState to reach 'complete'.
Returns Promise
resizeWindow
Section titled “resizeWindow”Resizes the browser viewport.
I.resizeWindow(1024, 768);Parameters
Section titled “Parameters”Returns Promise
rightClick
Section titled “rightClick”Performs a right-click on an element matched by locator.
I.rightClick('Menu');Parameters
Section titled “Parameters”locator(string | object) clickable element located by text, or any element located by CSS|XPath|strict locator.context(string? | object) (optional,nullby default, currently ignored by this helper).
Returns Promise
saveElementScreenshot
Section titled “saveElementScreenshot”Saves a screenshot of a single element to the output folder.
I.saveElementScreenshot('#logo', 'logo.png');Parameters
Section titled “Parameters”locator(string | object) element located by CSS|XPath|strict locator.fileNamestring file name to save.
Returns Promise
saveScreenshot
Section titled “saveScreenshot”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');Parameters
Section titled “Parameters”fileNamestring file name to save.
Returns Promise
scrollPageToBottom
Section titled “scrollPageToBottom”Scrolls to the bottom of the page.
I.scrollPageToBottom();Returns Promise
scrollPageToTop
Section titled “scrollPageToTop”Scrolls to the top of the page.
I.scrollPageToTop();Returns Promise
scrollTo
Section titled “scrollTo”Scrolls to the element matched by locator, or to given coordinates.
I.scrollTo('#submit');I.scrollTo(100, 200);Parameters
Section titled “Parameters”locator(string | object | number) element to scroll to, or an X coordinate if no element.offsetXnumber X offset, or Y coordinate iflocatoris a number.offsetYnumber 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 pageI.see('Welcome', '.content'); // text inside .content divI.see('Register', {css: 'form.register'}); // use strict locatorParameters
Section titled “Parameters”textstring expected on page.context(string? | object) (optional,nullby default) element located by CSS|Xpath|strict locator in which to search for text.
Returns Promise
seeAttributesOnElements
Section titled “seeAttributesOnElements”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' });Parameters
Section titled “Parameters”locator(string | object) element located by CSS|XPath|strict locator.attributesobject object with attribute names and expected values.
Returns Promise
seeCheckboxIsChecked
Section titled “seeCheckboxIsChecked”Verifies that the specified checkbox is checked.
I.seeCheckboxIsChecked('Agree');I.seeCheckboxIsChecked('#agree'); // I suppose user agreed to termsI.seeCheckboxIsChecked({css: '#signup_form input[type=checkbox]'});Parameters
Section titled “Parameters”Returns Promise
seeClipboardEquals
Section titled “seeClipboardEquals”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).
Parameters
Section titled “Parameters”textstring value to check.
Returns Promise
seeCookie
Section titled “seeCookie”Checks that a cookie with the given name is set.
Parameters
Section titled “Parameters”namestring cookie name.
Returns Promise
seeCssPropertiesOnElements
Section titled “seeCssPropertiesOnElements”Checks that all elements matched by locator have the given CSS properties.
I.seeCssPropertiesOnElements('h3', { 'font-weight': 'bold', display: 'block' });Parameters
Section titled “Parameters”locator(string | object) element located by CSS|XPath|strict locator.cssPropertiesobject object with CSS properties and their values to check.
Returns Promise
seeCurrentPathEquals
Section titled “seeCurrentPathEquals”Checks that current url path (ignoring query string and hash) equals to provided one.
I.seeCurrentPathEquals('/info');Parameters
Section titled “Parameters”pathstring value to check.
Returns Promise
seeCurrentUrlEquals
Section titled “seeCurrentUrlEquals”Checks that current url is equal to provided one.
Unlike seeInCurrentUrl performs a strict comparison.
I.seeCurrentUrlEquals('/register');Parameters
Section titled “Parameters”urlstring value to check.
Returns Promise
seeElement
Section titled “seeElement”Checks that a given Element is visible. Element is located by CSS or XPath.
I.seeElement('#modal');Parameters
Section titled “Parameters”locator(string | object) located by CSS|XPath|strict locator.context(string? | object) (optional,nullby default) element to search in CSS|XPath|Strict locator.
Returns Promise
seeElementInDOM
Section titled “seeElementInDOM”Checks that a given Element is present in the DOM. Element is located by CSS or XPath.
I.seeElementInDOM('#modal');Parameters
Section titled “Parameters”Returns Promise
seeInClipboard
Section titled “seeInClipboard”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).
Parameters
Section titled “Parameters”textstring value to check.
Returns Promise
seeInCurrentUrl
Section titled “seeInCurrentUrl”Checks that current url contains a provided fragment.
I.seeInCurrentUrl('/register'); // we are on registration pageParameters
Section titled “Parameters”urlstring a fragment to check
Returns Promise
seeInField
Section titled “seeInField”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');Parameters
Section titled “Parameters”field(string | object) located by label|name|CSS|XPath|strict locator.value(string | object) value to check.context(string? | object) (optional,nullby default) element to search in CSS|XPath|Strict locator.
Returns Promise
seeInSource
Section titled “seeInSource”Checks that the current page contains the given string in its raw source code.
I.seeInSource('<h1>Green eggs & ham</h1>');Parameters
Section titled “Parameters”textstring value to check.
Returns Promise
seeInTitle
Section titled “seeInTitle”Checks that title contains text.
I.seeInTitle('Home Page');Parameters
Section titled “Parameters”textstring text value to check.
Returns Promise
seeNumberOfVisibleElements
Section titled “seeNumberOfVisibleElements”Asserts that an element appears a given number of times on the page, and that all matching elements are visible.
I.seeNumberOfVisibleElements('.buttons', 3);Parameters
Section titled “Parameters”locator(string | object) located by CSS|XPath|strict locator.numnumber expected number of elements.
Returns Promise
seeTraffic
Section titled “seeTraffic”Verifies that a certain request is part of network traffic.
// checking the request url contains certain query stringsI.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 dataI.amOnPage('https://openai.com/blog/chatgpt');I.startRecordingTraffic();await I.seeTraffic({ name: 'event', url: 'https://cloudflareinsights.com/cdn-cgi/rum', requestPostData: { st: 2, }, });Parameters
Section titled “Parameters”-
optsObject options when checking the traffic network.opts.namestring A name of that request. Can be any value. Only relevant to have a more meaningful error message in case of fail.opts.urlstring Expected URL of request in network trafficopts.parametersObject? Expected parameters of that request in network trafficopts.requestPostDataObject? Expected that request contains post data in network trafficopts.timeoutnumber? Timeout to wait for request in seconds. Default is 10 seconds.
Returns void automatically synchronized promise through #recorder
selectOption
Section titled “selectOption”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 labelI.selectOption('subscription', 'Monthly'); // match option by textI.selectOption('subscription', '0'); // or by valueI.selectOption('//form/select[@name=account]','Premium');I.selectOption('form select[name=account]', 'Premium');I.selectOption({css: 'form select[name=account]'}, 'Premium');Parameters
Section titled “Parameters”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,nullby default) element to search in CSS|XPath|Strict locator.
Returns Promise
setCookie
Section titled “setCookie”Sets cookie(s).
Can be a single cookie object or an array of cookies:
I.setCookie({name: 'auth', value: true});
// as arrayI.setCookie([ {name: 'auth', value: true}, {name: 'agree', value: true}]);Parameters
Section titled “Parameters”cookie(CodeceptJS.Cookie | Array<CodeceptJS.Cookie>) a cookie object or array of cookie objects.
Returns Promise
startRecordingTraffic
Section titled “startRecordingTraffic”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
startScreencast
Section titled “startScreencast”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();Parameters
Section titled “Parameters”optionsobject? {maxWidth: number, maxHeight: number, quality: number, everyNthFrame: number} — CDPPage.startScreencastpass-throughs.formatis always'png'.
Returns Promise
stopRecordingTraffic
Section titled “stopRecordingTraffic”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
stopScreencast
Section titled “stopScreencast”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();Parameters
Section titled “Parameters”optionsobject? {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 keydown → keypress → (value mutated) → input → keyup
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']);Parameters
Section titled “Parameters”keys(string | Array<string>) characters to type, either as a string or an array of characters.delaynumber? (optional) delay in milliseconds between key presses.
Returns Promise
uncheckOption
Section titled “uncheckOption”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');Parameters
Section titled “Parameters”field(string | object) checkbox located by label | name | CSS | XPath | strict locator.context(string? | object) (optional,nullby default) element located by CSS | XPath | strict locator.
Returns Promise
Pauses execution for a number of seconds.
I.wait(2); // waits 2 secsParameters
Section titled “Parameters”secnumber number of seconds to wait.
Returns Promise
waitCurrentPathEquals
Section titled “waitCurrentPathEquals”Waits for current url path (ignoring query string and hash) to equal to the expected.
I.waitCurrentPathEquals('/info', 2);Parameters
Section titled “Parameters”pathstring value to check.secnumber? (optional,options.waitForTimeoutby default) time in seconds to wait
Returns Promise
waitForCookie
Section titled “waitForCookie”Waits for a cookie with the given name to be set (by default waits for options.waitForTimeout seconds).
I.waitForCookie('auth', 5);Parameters
Section titled “Parameters”namestring cookie name.secnumber? (optional,options.waitForTimeoutby default) time in seconds to wait
Returns Promise
waitForDetached
Section titled “waitForDetached”Waits for an element to be removed from the DOM (by default waits for options.waitForTimeout seconds).
I.waitForDetached('#popup', 5);Parameters
Section titled “Parameters”locator(string | object) element located by CSS|XPath|strict locator.secnumber? (optional,options.waitForTimeoutby default) time in seconds to wait
Returns Promise
waitForElement
Section titled “waitForElement”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 secsParameters
Section titled “Parameters”locator(string | object) element located by CSS|XPath|strict locator.secnumber? (optional,options.waitForTimeoutby default) time in seconds to wait
Returns Promise
waitForFunction
Section titled “waitForFunction”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 secI.waitForFunction((count) => window.requests == count, [3], 5) // pass args and wait for 5 secParameters
Section titled “Parameters”fn(string | function) to be executed in browser context.argsOrSec(Array| number)? (optional) arguments for function or, if a number, seconds to wait.secnumber? (optional,options.waitForTimeoutby default) time in seconds to wait
Returns Promise
waitForInvisible
Section titled “waitForInvisible”Waits for an element to become invisible (by default waits for options.waitForTimeout seconds).
I.waitForInvisible('#popup', 5);Parameters
Section titled “Parameters”locator(string | object) element located by CSS|XPath|strict locator.secnumber? (optional,options.waitForTimeoutby default) time in seconds to wait
Returns Promise
waitForText
Section titled “waitForText”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');Parameters
Section titled “Parameters”textstring to wait for.secnumber? (optional,options.waitForTimeoutby default) time in seconds to waitcontext(string? | object) (optional) element located by CSS|XPath|strict locator.
Returns Promise
waitForVisible
Section titled “waitForVisible”Waits for an element to become visible (by default waits for options.waitForTimeout seconds).
I.waitForVisible('#popup', 5);Parameters
Section titled “Parameters”locator(string | object) element located by CSS|XPath|strict locator.secnumber? (optional,options.waitForTimeoutby default) time in seconds to wait
Returns Promise
waitInUrl
Section titled “waitInUrl”Waiting for the part of the URL to match the expected. Useful for SPA to understand that page was changed.
I.waitInUrl('/info', 2);Parameters
Section titled “Parameters”urlPartstring value to check.secnumber? (optional,options.waitForTimeoutby default) time in seconds to wait
Returns Promise
waitToHide
Section titled “waitToHide”Waits for an element to be hidden. Alias of waitForInvisible.
Parameters
Section titled “Parameters”locator(string | object) element located by CSS|XPath|strict locator.secnumber? (optional,options.waitForTimeoutby default) time in seconds to wait
Returns Promise
waitUrlEquals
Section titled “waitUrlEquals”Waits for the entire URL to match the expected (by default waits for options.waitForTimeout seconds).
I.waitUrlEquals('/info', 2);Parameters
Section titled “Parameters”urlPartstring value to check.secnumber? (optional,options.waitForTimeoutby default) time in seconds to wait
Returns Promise