Selector constructor

Creates a selector.

Selector( init [, options] )
Parameter Type Description
init Function | String | Selector | Snapshot | Promise Identifies a DOM node to be selected. See Initialize Selectors.
options (optional) Object See Selector Options.

The following example creates a selector from a CSS string for an element with ID username:

import { Selector } from 'testcafe';

const usernameInput = Selector('#username');

Initialize Selectors

You can initialize a selector with any of these objects.

  • A CSS selector string that matches one or several nodes.

    import { Selector } from 'testcafe';
    
    // A selector is created from a CSS selector string.
    const submitButton = Selector('#submit-button');
    
  • A regular function executed on the client side. This function must return a DOM node, an array of DOM nodes, NodeList, HTMLCollection, null or undefined.

    import { Selector } from 'testcafe';
    
    // A selector is created from a regular function.
    // This selector will take an element by id that is saved in the localStorage.
    const element = Selector(() => {
        const storedElementId = window.localStorage.storedElementId;
    
        return document.getElementById(storedElementId);
    });
    

    You can provide a function that takes arguments, and then pass serializable objects to the selector when you call it.

    import { Selector } from 'testcafe';
    
    const elementWithId = Selector(id => {
        return document.getElementById(id);
    });
    
    fixture `My fixture`
        .page `http://www.example.com/`;
    
    test('My Test', async t => {
        await t.click(elementWithId('buy'));
    });
    

    If the function should always use the same argument value, you can assign it to the options.dependencies property when the selector is created.

  • A selector.

    import { Selector } from 'testcafe';
    
    // This selector is created from a CSS selector
    // that matches all elements of a specified class.
    const ctaButton = Selector('.cta-button');
    
    // This selector is created based on the previous selector and inherits
    // its initializer, but overwrites the `visibilityCheck` parameter.
    Selector(ctaButton, { visibilityCheck: true });
    
  • A DOM Node Snapshot returned by selector execution.

    import { Selector } from 'testcafe';
    
    fixture `My fixture`
        .page `http://www.example.com/`;
    
    test('My Test', async t => {
        const topMenuSnapshot = await Selector('#top-menu')();
    
        // This selector is created from a DOM Node state object returned
        // by a different selector. The new selector will use the same initializer
        // as 'elementWithId' and will always be executed with the same parameter
        // values that were used to obtain 'topMenuSnapshot'. You can still
        // overwrite the selector options.
        const visibleTopMenu = Selector(topMenuSnapshot, {
            visibilityCheck: true
        });
    });
    
  • A promise returned by a selector.

    import { Selector } from 'testcafe';
    
    const elementWithIdOrClassName = Selector(value => {
        return document.getElementById(value) || document.getElementsByClassName(value);
    });
    
    fixture `My fixture`
        .page `http://www.example.com/`;
    
    test('My Test', async t => {
        // This selector is created from a promise returned by a call to a
        // different selector. The new selector will be initialized with the
        // same function as the old one and with hard-coded parameter values
        // as in the previous example.
        const submitButton = Selector(elementWithIdOrClassName('main-element'));
    });
    

Options

options.boundTestRun

Type: Object

If you need to call a selector from a Node.js callback, assign the current test controller to the boundTestRun option.

For more information, see Calling Selectors from Node.js Callbacks.

options.dependencies

Type: Object

Use this option to pass functions, variables or objects to selectors initialized with a function. The dependencies object's properties are added to the function's scope as variables.

Use dependencies instead of the function's arguments if you do not need to pass new values every time you call the selector.

The following sample demonstrates a selector (element) that uses a server-side object passed as a dependency (customId) to obtain a page element.

import { Selector } from 'testcafe';

const persistentId = { key: 'value' };

const element = Selector(() => {
    return getElementByCustomId(persistentId);
}, {
    dependencies: { persistentId }
});

fixture `My fixture`
    .page `http://www.example.com/`;

test('My Test', async t => {
    await t.click(element);
});

options.timeout

Type: Number

The time (in milliseconds) allowed for an element returned by the selector to appear in the DOM before the test fails.

If the visibilityCheck option is enabled, the element then must become visible within the timeout.

Default value: the timeout specified in the runner.run API method or the --selector-timeout command line option.

options.visibilityCheck

Type: Boolean

true to additionally require the returned element to become visible within options.timeout.

This option is in effect when TestCafe waits for the selector to return a page element. This includes situations when

  • a property is obtained from the selector;

    const width = await Selector('#element', { visibilityCheck: true }).clientWidth;
    
  • a selector property is passed to an assertion as its actual value;

    await t.expect(Selector('#element', { visibilityCheck: true }).clientWidth).eql(400);
    
  • a selector is evaluated with the await keyword;

    const snapshot = await Selector('#element', { visibilityCheck: true })();
    

If the target element is not visible, the selector throws an exception.

Note that when a selector is passed to a test action as the target element's identifier, the target element should be visible regardless of the visibilityCheck option.

Unlike filter functions, the visibilityCheck option does not change the selector's matched set.

Consider the following page:

<html>
  <body>
    <div>This div is visible</div>
    <div style="display:none">This div not is visible</div>
    <div style="visibility:hidden">This div not is visible either</div>
  </body>
</html>

When you use a selector with visibilityCheck enabled to determine if an element exists or to count matching elements, TestCafe also takes into account invisible elements.

const count = await Selector('div', { visibilityCheck: true }).count;

// returns 3 since the visibilityCheck option
// does not affect the selector's matched set

To filter page elements by their visibility, use filterVisible and filterHidden methods.

Default value: false