Edit on GitHub

testium-driver-wd

General Notes

browser is just a wd session with some additional helpers. Which means that all methods in the wd docs are expected to work. This page omits many things that are already part of wd.

All methods return a Promise that can be chained. So whenever it says “returns a string”, read “returns the promise of a string”. The wd docs have more examples for what that means. This also implies that the returned promises have to be passed to the test runner (e.g. mocha), either by using async functions and await or by returning the promise.

Another thing to keep in mind is to always use browser.loadPage and never browser.get to load a page. The reason is that browser.loadPage will properly capture status code and headers whereas browser.get will not. This is different from using wd directly because capturing status codes is not a native wd feature.

browser.capabilities

An object describing the WebDriver capabilities that the current browser supports.

This is not a promise, but a plain JavaScript object.

Example: Capability Check

before(function requiresAlerts() {
  // Skip the current test suite unless the browser can work with alerts
  if (!browser.capabilities.handlesAlerts) this.skip();

  // skip when not Chrome browser
  if (browser.capabilities.browserName !== 'chrome') this.skip();
});

browser.sessionCapabilities(): Promise<browser.capabilities>

Returns browser.capabilities.

const capabilities = await browser.sessionCapabilities();

browser.getConsoleLogs([logLevel: string]): Promise<ConsoleLogObj[]|ConsoleLogObj>

Returns all log events for logLevel all(default) log,warn, error, debug since the last time this method was called.

interface ConsoleLogObj {
  type: 'error' | 'warn' | 'log' | 'debug',
  message: string
  source: string
  timestamp: number
}

Example:

const errorLogs = await browser.getConsoleLogs('error');

⚠️ Warning:

  • Each browser implements this differently against the WebDriver spec.
  • Logs are not persistent, and can’t be retrieved multiple times.
const errorLogs = await browser.getConsoleLogs('error');    // retrieve existing errors

const emptyErrors = await browser.getConsoleLogs('error');  // Will not contain the previous errors logs

browser.getScreenshot(): Promise<string>

Returns screenshot as a base64 encoded PNG.

browser.getHeader(name: string): Promise<any>

Returns the value of the response header with the provided name. Header names should be provided in lowercase.

const country = await browser.loadPage('/').getHeader('x-country')

browser.getHeaders(): Promise<Record<string, any>>

Returns all response headers for the current page as a plain object. All keys in the object will be lowercase, e.g. content-type instead of Content-Type.

const headers = await browser.loadPage('/').getHeaders()

browser.getPath(): Promise<string>

Returns the current path and query of the page, e.g. /some/route?foo=bar.

Added in: Testium-driver-wd v3.1.0 browser.getPath() will return the path including hash, e.g. /some/route?foo=bar#hash

browser.getUrl(): Promise<string>

Returns the current absolute url of the page, e.g. http://localhost:1234/some/route.

const url = await browser.getUrl();

assert.ok(/^https:/.test(url));

assert.match(url, /^https:/);   // Node v12.16.0+

browser.getUrlObject(): Promise<URLObject>

Added in: Testium-driver-wd v3.1.0

Returns a WHATWG URL instance of the current url.

const urlObj = browser
  .loadPage('/#abc')
  .clickOn('#something')    // do something that changes the url
  .getUrlObject();

browser.getStatusCode(): Promise<number|undefined>

Returns the response status code for the current page.

const statusCode = await browser.loadPage().getStatusCode();

browser.loadPage(url: string, options?: loadPageOpts): Promise<void>

Navigates the browser to the specified relative or absolute url.

await browser.loadPage('/products');   // implies assertStatusCode(200)

The following loadPageOpts options are supported:

  • query: An object with additional query parameters.
  • headers: An object with headers to inject.
  • expectedStatusCode: Defaults to 200, can be one of:
    • An integer status code that the response should equal
    • A RegExp that the status code (as a string) should match
    • A Function which takes the status code and returns true or false if it is acceptable

Examples

// expecting status code
await browser.loadPage('/page', { expectedStatusCode: 500 });

// passing queries
await browser.loadPage('/page', { query: { foo: 'bar' }});

// passing headers
await browser.loadPage('/page', { headers: { 'x-foo': 'bar' }});

Example: Running loadPage in Mocha before hook

To speed up your tests and short circuit test failures, run loadPage in the Mocha before hook.

Note: Neither screenshot nor HTML page will be created in case there is an error in Mocha hooks.

describe('products', () => {
  before(browser.beforeHook());

  before(() =>
    browser.loadPage('/products')
  );

  it('works 1', /* ... */);
  it('works 2', /* ... */);
  it('works 3', /* ... */);
});

Example: Relative URL with Headers

If relative, the root is assumed to be http://127.0.0.1:#{app.port}, where app.port refers to the config option.

// Navigates to `http://127.0.0.1:${app.port}/products`
// passing along the `X-Custom-Header: Some Value` header.
await browser
  .loadPage('/products', { headers: { 'x-custom-header': 'Some-Value' } });

browser.refresh(): Promise<void>

Refresh the current page.

await browser
  .loadPage('/')
  .clickOn('#something')    // does something that changes the page
  .refresh();               // reload the current page

browser.waitForPath(path: string|RegExp, timeout=5000: number): Promise<void>

Waits timeout ms for the browser to be at the specified path.

await browser.waitForPath('/foo');
await browser.waitForPath('/foo', 10000);   // with increased timeout

browser.waitForUrl(url: string|RegExp, query?: Record<string, string|number>, timeout=5000: number): Promise<void>

Waits timeout ms for the browser to be at the specified url. Using query instead of passing the query params in the url allows the test to accept any order of query parameters.

Example: Order Doesn’t Matter

browser
  .loadPage('/products?count=15&start=30')
  // This will return immediately even though the order of `count` and `start`
  // is reversed.
  .waitForUrl('/products', { start: 30, count: 15 });

Elements

browser.clickOn(selector: string): Promise<void>

Calls native click() on the Element found by the given selector.

await browser.clickOn('.button');

Changed in: Testium-driver-wd v3.0.0 The selector passed into clickOn() must match only one unique element in the page. Otherwise onClick() will throw. Use clickOnAll() for multiple elements.

browser.clickOnAll(selector: string): Promise<void>

Added in: Testium-driver-wd v3.0.0

Calls native click() on each Element found by the given selector.

await browser.clickOnAll('.foo, .bar, .elm');

browser.moveTo(selector: string, xOffset?: number, yOffset?: number): Promise<void>

Move the mouse by an offset of the specified element found by the given selector. xOffset and yOffset are optional.

await browser.moveTo('.button');

browser.getElement(selector: string): Promise<Element>

Finds an element on the page using the selector and returns an Element. If it fails to find an element matching the selector, it will reject with an error.

const button = await browser.getElement('.button');
await button.isDisplayed();

// or as a promise chain
await browser.getElement('.button').isDisplayed();

browser.getElementOrNull(selector: string): Promise<Element|null>

Finds an element on the page using the selector. Returns null if the element wasn’t found.

const button = await browser.getElementOrNull('.button1,.button2')
if (button) {
  assert.strictEqual(await button.text(), 'OK');
}

browser.getElements(selector: string): Promise<Element[]>

Finds all elements on the page using the selector and returns an array of Elements.

browser.waitForElementDisplayed(selector: string, timeout=3000: number): Promise<Element>

Waits for the element at selector to exist and be visible, then returns the Element. Times out after timeout ms.

await browser.waitForElementDisplayed('.foo');
await browser.waitForElementDisplayed('.bar', 5000);

browser.waitForElementNotDisplayed(selector: string, timeout=3000: number): Promise<Element>

Waits for the element at selector to exist and not be visible, then returns the Element. Times out after timeout ms.

await browser.waitForElementNotDisplayed('.foo');
await browser.waitForElementNotDisplayed('.bar', 5000);

browser.waitForElementExist(selector: string, timeout=3000: number): Promise<Element>

Waits for the element at selector to exist, then returns the Element. Times out after timeout ms. Visibility is not considered.

await browser.waitForElementExist('.foo');
await browser.waitForElementExist('.bar', 5000);

browser.waitForElementNotExist(selector: string, timeout=3000: number): Promise<null>

Waits for the element at selector to not exist, then returns null. Times out after timeout ms.

await browser.waitForElementNotExist('.foo');

browser.assertElementHasText(selector: string, textOrRegex: string|RegExp): Promise<Element>

Asserts that the element at selector contains textOrRegex. Returns the Element

Throws exceptions if selector doesn’t match a single node, or that node does not contain the given textOrRegex.

await browser.assertElementHasText('.user-name', 'someone');
// is the same as:
assert.strictEqual(await browser.getElement('.user-name').text(), 'someone');

browser.assertElementLacksText(selector: string, textOrRegex: string|RegExp): Promise<Element>

Asserts that the element at selector does not contain textOrRegex. Returns the Element.

Inverse of assertElementHasText.

await browser.assertElementLacksText('.user-name', 'someone');

browser.assertElementHasValue(selector: string, textOrRegex: string|RegExp): Promise<Element>

Asserts that the element at selector does not have the value textOrRegex. Returns the Element.

Throws exceptions if selector doesn’t match a single node, or that node’s value is not textOrRegex.

await browser.assertElementHasValue('.user-name', 'someone else');
// is the same as:
assert.strictEqual(browser.getElement('.user-name').value(), 'someone else');

browser.assertElementLacksValue(selector: string, textOrRegex: string|RegExp): Promise<Element>

Asserts that the element at selector does not have the value textOrRegex. Returns the Element.

Inverse of assertElementHasValue.

await browser.assertElementLacksValue('.user-name', 'someone else');

browser.assertElementHasAttribute(selector: string, attribute: string): Promise<Element>

Asserts that the element at selector has a specific attribute. Returns the Element.

Throws an exception when the selector doesn’t match a single node, or the attribute is not of type string.

await browser.assertElementHasAttribute('.user-name', 'name');

browser.assertElementHasAttributes(selector: string, attributes: Record<string, any>): Promise<Element>

Asserts that the element at selector contains attribute:value pairs specified by attributes object. Returns the Element.

Throws exceptions if selector doesn’t match a single node, or that node does not contain the given attribute:value pairs.

await browser.assertElementHasAttributes('.user-name', {
  text: 'someone',
  name: 'username',
});

browser.assertElementLacksAttribute(selector: string, attribute: string): Promise<Element>

Asserts that the element at selector lacks a specific attribute. Returns the Element.

Throws an exception when the selector doesn’t match a single node, or the attribute is not of type string.

await browser.assertElementLacksAttribute('.user-name', 'data-name');

browser.assertElementLacksAttributes(selector: string, attributes: string[]): Promise<Element>

Asserts that the element at selector lacks a list of attributes. Returns the Element.

Throws exceptions when the selector doesn’t match a single node, or the attributes argument is not an array of strings.

await browser.assertElementLacksAttributes('.user-name', ['data-name', 'alt']);

browser.assertElementIsDisplayed(selector: string): Promise<Element>

Asserts that the element at selector exists and is visible. Returns the Element.

await browser.assertElementIsDisplayed('.user-name');
// is the same as
assert.ok(await browser.getElement('.user-name').isDisplayed());

browser.assertElementNotDisplayed(selector: string): Promise<Element>

Asserts that the element at selector is not visible. Returns the Element.

Inverse of assertElementIsDisplayed.

browser.assertElementExists(selector: string): Promise<Element>

Asserts that the element for selector exists.

await browser.assertElementExists('.user-name');

browser.assertElementDoesntExist(selector: string): Promise<null>

Asserts that the element for selector doesn’t exist.

Inverse of assertElementExists.

await browser.assertElementDoesntExist('.user-name');

browser.assertElementsNumber(selector: string, number: number): Promise<Element[]>

Asserts that selector matches exactly number elements.

await browser.assertElementsNumber('.foo', 3);  // must have exactly 3 elements

browser.assertElementsNumber(selector:string, {min?: number, max?: number, equal?: number}): Promise<Element[]>

Added in: Testium-driver-wd v3.0.0

Asserts that selector matches element numbers:

  • min: at least min amount of elements
  • max: at most max amount of elements
  • equal: exactly equal amount of elements
await browser.assertElementsNumber('.foo', { min: 1 });     // must have at least 5 elements
await browser.assertElementsNumber('.bar', { max: 5 });     // can have up to 5 elements
await browser.assertElementsNumber('.elm', { equal: 3 });   // must have exactly 3 elements

Forms

browser.clear(selector: string): Promise<Element>

Clears the input found by the given selector.

const value = await browser
  .clear('#input1')
  .getValue();

browser.fillFields(fields: Record<string, string>): Promise<Element>

Convenience method for setting the value for multiple form fields at once. fields is an object that maps css selectors to values.

browser.fillFields({
  '.first-name': 'Jamie',
  '.last-name': 'Smith',
});
// Equivalent to:
browser
  .setValue('.first-name', 'Jamie')
  .setValue('.last-name', 'Smith');

browser.setValue(selector: string, value: string|number): Promise<Element>

Alias: browser.clearAndType

Sets the value of the Element with the given selector to value.

browser
  .setValue('.first-name', 'John')
  .setValue('.last-name', 'Smith')
  .clickOn('.submit');

browser.type(selector: string, value: string|number): Promise<Element>

Sets a value to the form element found for selector selector.

const value = await browser
  .type('#input1', 'foo')
  .getValue();

Page

browser.getPageTitle(): Promise<string>

Returns the current page title.

const title = await browser.getPageTitle();

assert.strictEqual(title, 'foo')

browser.getPageSource(): Promise<string>

Returns the current page’s html source. Using this method usually means that you are trying to test something that can be done without a browser.

const pageSource = await browser.getPageSource();

assert.match(pageSource, /body/);

Note that if the browser is presenting something like an XML or JSON response, this method will return the presented HTML, not the original XML or JSON response. If you need to simply test such a response, use a simpler test that doesn’t involve a browser. For example, you could use a normal HTTP client library to load a URL relative to browser.appUrl.

browser.getPageSize(): Promise<{width: number, height: number}>

Returns the current window’s size as an object with height and width properties in pixels.

const pageSize = await browser.getPageSize();

assert.deepStrictEqual(pageSize, { width: 800, height: 600 });

This can be useful for responsive UI testing when combined with browser.setPageSize. Testium defaults the page size to height: 1000 and width: 1400.

browser.setPageSize({height?: number, width?: number}): Promise<void>

Sets the current window’s size in pixels.

// Resize window to a much smaller screen
await browser
  .setPageSize({ height: 400, width: 200 })
  .loadPage('/');

// Adjust the width only
await browser
  .setPageSize({ width: 200 })
  .loadPage('/');

Evaluate

Note that client-side functions will not have access to server-side values. Return values have to cleanly serialize as JSON, otherwise the behavior is undefined.

browser.evaluate(code: string): Promise<any>

Warning: Consider using the function variant below. Having code with proper syntax highlighting and linting can prevent frustrating debugging sessions.

Executes the given javascript code. It must contain a return statement in order to get a value back.

const code = 'return document.querySelector(\'.menu\').style;';
const style = await browser.evaluate(code);

browser.evaluate(args…, function(args…)): Promise<any>

Returns the result of the given function, invoked on the webdriver side (so you cannot bind its this object or access context variables via lexical closure). If you provided args, Testium will marshals them as JSON and passes them to the function in the given order.

Example: Messing With Globals

// Patching global state to influence the app's behavior.
browser.evaluate(function fakeConfigData() {
  window.myConfigBlob.magicalSetting = true;
});

Example: Passing Arguments

// This will return the current url fragment
const hash = await browser.evaluate('hash', function getLocationProp(prop) {
  return window.location[prop];
});

// Passing multiple arguments
browser.evaluate('http://foo.bar', '/', '#hash', (domain, path, hash) => {
  window.location.href = `${domain}${path}${hash}`;
});

browser.evaluateAsync(args…, function(args…)): Promise<void>

The executed script is required to return a Promise.

Returns a Promise of the given function, invoked on the webdriver side (so you cannot bind its this object or access context variables via lexical closure). If you provided args, Testium will marshal them as JSON and pass them to the function in the given order.

Note: NOT supported on PhantomJS

Example: Fetch the data

// Fetching data from the client
browser.evaluateAsync(async () => {
  const response = await fetch('http://example.com/movies.json');
  return response.json();
});

Example: Passing Arguments

// Return the result after 1 sec
browser.evaluateAsync(3, 6, (a, b) => {
  // return a Promise
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(a * b);
    }, 1000);
  })
});

Cookies

Cookie objects have the following interface:

interface Cookie {
  name: string
  value: string
  path: string | '/'
  domain: string | '127.0.0.1'
  secure: boolean | false
  expiry: number
  httpOnly: boolean
}

Note that the interface shown above is Testium-specific and only applies when using setCookieValue() or setCookieValues()

browser.setCookieValue(name :string, value: string, options?: Record<string, any>): Promise<void>

Sets a cookie on the current page’s domain to the value given. The argument options can overwrite any of the Cookie object properties.

browser
  .setCookieValue('userId', '3')                        // set before loading the page
  .setCookieValue('secureIt', '3',  { secure: true })   // set secure cookie
  .loadPage('/');

browser.setCookieValues(Record<string, string>): Promise<void>

Given an object mapping cookie names to values, sets multiple cookies by calling setCookieValue() the requisite number of times for you.

browser
  .setCookieValues({
    userId: '3',
    dismissedPopup: 'true',
  })
  .loadPage('/');

browser.getCookie(name: string): Promise<Cookie|null>

Returns a Cookie object.

const cookie = await browser.getCookie('foo');

assert.strictEqual(cookie.value, 'bar');

browser.getCookies(): Promise<Cookie[]>

Returns an array of Cookie objects:

const cookies = await browser.getCookies();

assert.ok(cookies.every(cookie => cookie.secure));

browser.clearCookie(name: string): Promise<void>

Deletes a cookie by name.

browser.clearCookie('_ga');

browser.clearCookies(): Promise<void>

Deletes all cookies.

browser.clearCookies();

Alerts & Confirms

This API allows you to interact with alert, confirm, and prompt dialogs.

Some browsers, notably phantomjs, don’t support this part of the WebDriver spec. You can guard against this by checking the Capabilities object.

describe('Alert-based tests', function() {
  before(browser.beforeHook());

  before(function requiresAlerts() {
    // Skip the current test suite unless the browser can work with alerts
    if (!browser.capabilities.handlesAlerts) this.skip();
  });

  // <insert actual test cases here>
});

browser.getAlertText(): Promise<string>

Get the text of a visible alert, prompt, or confirm a dialog.

const alertText = await browser.getAlertText();

browser.acceptAlert(): Promise<void>

Accepts a visible alert, prompt, or confirm a dialog.

browser.acceptAlert();

browser.dismissAlert(): Promise<void>

Dismisses a visible alert, prompt, or confirm dialog.

browser.dismissAlert();

browser.typeAlert(value: string): Promise<void>

Types into a visible prompt dialog.

browser.typeAlert('');

Windows & Frames

browser.closeWindow(): Promise<void>

Close the currently focused window.

browser
  .clickOn('#open-popup')
  .switchToWindow('popup1')
  .closeWindow()
  .switchToDefaultWindow();

The name used to identify the popup can be set in the code used to create it. It’s the strWindowName in window.open(strUrl, strWindowName, [strWindowFeatures]).

browser.switchToDefaultFrame(): Promise<void>

Switch focus to the default frame (i.e. the actual page).

browser
  .switchToFrame('some-frame')
  .clickOn('#some-button-in-frame')
  .switchToDefaultFrame();

browser.switchToFrame(id: string): Promise<void>

Change focus to another frame on the page.

browser.switchToFrame('some-frame');

browser.switchToDefaultWindow(): Promise<void>

Switch focus to the window that was most recently referenced by loadPage. Useful when interacting with popup windows.

browser
  .loadPage('/path')
  .clickOn('#open-popup')
  .switchToWindow('popup1')
  .clickOn('#some-button-in-popup')
  .closeWindow()
  .switchToDefaultWindow();

browser.switchToWindow(name: string): Promise<void>

Switch focus to the window with name name.

await browser.switchToWindow('popup1');

Lighthouse & Puppeteer

Lighthouse and Puppeteer require Chromedriver and headless Chrome to be present in the environment.

browser.emulate(deviceDescriptor: string): Promise<void>

Emulates a device given its name. A list of device descriptor names can be found at puppeteers deviceDescriptors

browser.emulate('iPhone X').loadPage();

browser.withPuppeteerPage(function(page: PuppeteerPage): any): Promise<void>

Connects Puppeteer to the Chromedriver and exposes the Puppeteer Page api

await browser.withPuppeteerPage(page => {/* ... */});

browser.getLighthouseData(flags?: Record<string, any>, config? Record<string, any>): Promise<LHResultObj>

Returns Lighthouse and returns Lighthouse raw result data. Information regarding flags and config can be found in the official Lighthouse docs

It is advised to increase the Mocha test timeout when running more than one Lighthouse audit at once.

const flags = {
  chromeFlags: [
    '--disable-gpu',
    '--headless',
    '--disable-storage-reset',
    '--enable-logging',
    '--disable-device-emulation',
    '--no-sandbox',
  ],
};
const config = {
  extends: 'lighthouse:default',
  settings: {
    onlyCategories: ['performance', 'seo', 'accessibility'],
    throttlingMethod: 'simulate',
  },
};

it('my Lighthouse test', async function() {
  this.timeout(20000); // set Mocha timeout to 20 seconds

  const rawResults = await browser
    .loadPage('/')
    .getLighthouseData(flags, config);
  
  // ...
});

browser.runLighthouseAudit(flags?: Record<string, any>, config? Record<string, any>): Promise<parsedLHResultObj>

Runs the lighthouse tests on the current page loaded by loadPage and resolves to a result object containing score and list of error list.

const rawResults = await browser
  .loadPage('/path')
  .runLighthouseAudit();

By default, the audit is running in “Mobile” mode. To run in “Desktop” mode, we need to pass the --disable-device-emulation flag as shown in the example below.

let lhResults;

before(async () => {
  lhResults = await browser
    .loadPage('/path')
    .runLighthouseAudit({
      chromeFlags: ['--disable-device-emulation'],  // To run audit in Desktop mode
    });
});

it(`checking for score over 85`, () =>
  assert.ok(lhResults.isSuccess(85), `score is only ${lhResults.score}`)
);

it(`There are no errors`, () =>
  assert.strictEqual(Object.keys(lhResults.errors()).length, 0)
);

parsed LH result object

interface parsedLHResultObj {
  score: number                                 // Success score (success / total)
  audits: Record<string, Object>                // Raw Lighthouse audit results
  errors(): Record<string,any>[]                // Returns an array of all failed audit results
  errors(audit :string): Record<string,any>     // Returns a specific failed audit
  errorString(): string
  isSuccess(expectedScore: number): boolean     // Asserts that the results meet the expected score
  success(): Record<string, any>[]              // Returns an array of all successful audit results
  success(audit: string): Record<string, any>   // Returns a specific audit result
}

browser.a11yAudit({ignore?: function|string[], flags?: Record<string, any>, config? Record<string, any>}): Promise<Object[]|[]>

Runs the accessibility issues on the current page loaded by loadPage. flags, config and ignore are optional parameters.

ignore is the ids of issues to ignore, a string array

const issues = await browser
  .loadPage('/path')
  .a11yAudit();

assert.strictEqual(issues.length, 0);
const issues = await browser
  .loadPage('/path')
  .a11yAudit({ 
    ignore: ['color-contrast', 'meta-viewport'],    // ignore 'color-contrast' and 'meta-viewport'
  });

assert.strictEqual(issues.length, 0);

assertAccessibilityScore(minScore: number, skipAudits: string[]): Promise<parsedLHResultObj>

Runs Lighthouse accessibility audit.

await browser.loadPage('/').assertAccessibilityScore(40);

To disable specific audits, pass the optional array containing the category’s audit IDs. Accessibility audit IDs

await browser.loadPage('/').assertAccessibilityScore(40, ['listitem']);

assertBestPracticesScore(minScore: number, skipAudits: string[]]): Promise<parsedLHResultObj>

Runs Lighthouse Best Practices audit.

await browser.loadPage('/').assertBestPracticesScore(40);

To disable specific audits, pass the optional array containing the category’s audit IDs. Best Practices audit IDs

await browser.loadPage('/').assertBestPracticesScore(40, ['js-libraries']);

assertPerformanceScore(minScore: number, skipAudits: string[]): Promise<parsedLHResultObj>

Runs Lighthouse Performance audit. The following performance audits are skipped by default: final-screenshot, is-on-https, screenshot-thumbnails,

await browser.loadPage('/').assertPerformanceScore(40);

To disable specific audits, pass the optional array containing the category’s audit IDs. Performance audit IDs

await browser.loadPage('/').assertPerformanceScore(40, ['font-display']);

assertPwaScore(minScore: number, skipAudits: string[]): Promise<parsedLHResultObj>

Runs Lighthouse PWA audit.

await browser.loadPage('/').assertPwaScore(40);

To disable specific audits, pass the optional array containing the category’s audit IDs. PWA audit IDs

await browser.loadPage('/').assertPwaScore(40, ['apple-touch-icon']);

assertSeoScore(minScore: number, skipAudits: string[]): Promise<parsedLHResultObj>

Runs Lighthouse SEO audit.

await browser.loadPage('/').assertSeoScore(40);

To disable specific audits, pass the optional array containing the category’s audit IDs. SEO audit IDs

await browser.loadPage('/').assertPwaScore(40, ['structured-data']);

Element Promise Chain

element.click(): Node

Clicks on the element, e.g. clicking on a button or a dropdown.

const element = await browser.getElement('#foo');
element.click();

element.get(attribute: string): Promise<any>

Returns the element’s specified HTML attribute, e.g. “value”, “id”, or “class”.

const classAttribute = await element.get('class');

element.getElement(selector: string): Promise<Element>

Returns first child element matching selector.

const firstChild = await element.getElement('.foo');

element.getElementOrNull(selector: string): Promise<Element>

Returns first child element matching selector or null.

const firstChild = await element.getElementOrNull('.foo');

element.getElements(selector: string): Promise<Element[]>

Returns list of child elements matching selector.

const listElements = await element.getElements('li');

element.text(): Promise<string>

Returns the element’s text contents.

Note that WebDriver (and therefore Testium) will not return text of hidden elements.

const text = await element.text();

element.isDisplayed(): Promise<boolean>

Returns true if the element is visible.

const element = await browser.getElement('#foo');
if (await element.isDiplayed()) {
  // do something
} else {
  // do something else
}

element.clear(): Promise<void>

Clears the input element.

const element = await browser.getElement('#input1');
await element.clear();

element.type(value: string): Promise<void>

Type text to the input element.

const element = await browser.getElement('#input1');
await element.type('foo');