Devendra174's picture
Upload folder using huggingface_hub
1e92f2d verified



Style Guide

Variable naming

Variables that derive from a page/component/flow object (eg. SidebarComponent) should be named after the object following camelCase convention.

Avoid:

const bar = new SidebarComponent( page );
const mhp = new MyHomePage( page );

Instead:

const sidebarComponent = new SidebarComponent( page );
const myHomePage = new MyHomePage( page );

Use async/await

We use async functions and await to wait for commands to finish. This lets asynchronous methods execute like synchronous methods. For every method which returns a promise or thenable object await should be used. Keep in mind that await is only valid inside async function.

We don't chain function calls together and avoid using .then calls.

Avoid:

async function openModal() {
    const modal = await this.page.waitForSelector( 'modal-open' );
    await modal.click().then( () => this.page.waitForSelector( 'modal-is-open' ) );
}

Instead:

async function openModal() {
    const modal = await this.page.waitForSelector('modal-open');
    await modal.click();
    await this.page.waitForSelector( 'modal-is-open' ) );
}

Selectors

Selectors are the core of automated e2e testing. The Playwright project has an excellent documentation page on selectors and best practices.

Ideally, a selector satisfies all of the following:

  • unique: one selector, one element.
  • reliable: the same element is selected with each iteration.
  • brief: selector is short and easy to read.

The following guidance are in addition to suggestions by the Playwright project.

No selectors within class definition

Place selectors within the same file, but outside of the class representing the object. Never place a selector within the class definition itself.

For examples see EditorPage or NotificationComponent.

Avoid:

class SomeObject() {
    submitButtonSelector: 'button[type="submit"]'
}

Instead:

const selectors = {
    submitButton: 'button[type="submit"]',
};

class SomeObject() {
    async someMethod(): {
        await this.page.click( selectors.submitButton )
    }
}

Extract repetitive selectors

While one-off selectors within a code block is acceptable, if the same selector is used more than twice, move the selector into the selectors object:

Avoid:

class SomeObject() {
    async doSomething() {
        await this.page.click( '#submit' );
    }

    async doSomethingElse() {
        await this.page.click( '#submit' ); // Notice the #submit selector is used twice.
    }
}

Instead:

const selectors = {
    submitButton: '#submit', // Move it into the `selectors` object.
}

class SomeObject() {
    async doSomething() {
        await this.page.click( selectors.submitButton );
    }

    async doSomethingElse() {
        await this.page.click( selectors.submitButton );
    }
}

Do not use Xpath

This is simple; do not use Xpath selectors.

Avoid:

const locator = page.locator( '//button' );

Instead:

await locator = page.locator( 'button' ); // or 'button[type="submit"]' or literally anything else.

Prefer user-facing selectors

Where possible, prefer user-facing attributes such as ARIA, user-facing text, role selectors. Use CSS selectors as last resort if no other suitable selectors can be found.

See also: the Playwright maintainers' definitive guide.

Avoid:

await page.click( 'div.someclass .yet-another-class .attribute .very-long-attribute' );
await page.click( 'button .is-highlighted' );

Instead:

await page.click( 'button:has-text("Submit")' ); // Text based selector.
await page.click( 'button[aria-label="Some Class"]' ); // ARIA selector.
await page.click( 'role=spinbutton[name="Continue"]' ); // Role-based selector.

Naming

Name selectors based on function, type and description. Try to avoid using element location unless multiple similar buttons exist. This way the selector name does not become outdated if the UI changes.

Do not append the term 'Selector' or similar to the selector name. It is redundant.

Avoid:

const selectors = {
    contactButtonOnHeaderPane: '.button contact-us', // What if the button moves?
    secondButtonOnPopupSelector: '.button send-form', // Breaks the 'selector' sub-rule.
    select: 'select.month', // Not descriptive at all.
};

Instead:

const selectors = {
    contactUsButton: '.button contact-us',
    submitFormButton: '.button send-form',
    monthSelect: 'select.month',
};

Involve minimal selectors in methods

When method(s) need to wait on an element on the page, involve the minimal number of selectors as possible. Playwright has a strong auto-wait mechanism that handles 95% of the cases.

For instance, when loading the Calypso Media page:

  • Good: wait either on the gallery being present, or the thumbnails having generated.
  • Bad: wait on the header text and the gallery and the upload button and the thumbnails.

Avoid:

await this.page.waitForSelector( 'h1:has-text("New Page")' ); // Waiting for the h1 accomplishes nothing except to add another selector to complicate matters.
await this.page.fill( 'input[placeholder="New Text"]' );

Instead:

await this.page.fill( 'input[placeholder="New Text"]' );

Convert repetitive variations to dynamic selector

Combine similar or repetitive selectors into a dynamic selector. Dynamic selector is also useful when the target selector depends on a known conditional (eg. mobile/desktop, language).

Avoid:

const selectors = {
    submitButton: 'button:text("Submit")',
    cancelButton: 'button:text("Cancel")',
    pauseButton: 'button:text("Pause")',
    // Note the repetitive selectors varying only by text.
};

Instead:

const selectors = {
    button: ( action: string ) => `button:text("${ action }")`,
};

// then, in the POM

async funtion clickButton( text: string ) {
    await this.page.click( selectors.button( text ) );
}

Test steps

Only one top-level describe block

Only place one top/root-level describe block.

Multiple root-level describe blocks are a sign that the file needs to be split into smaller files or the flow re-examined.

Avoid:

describe('Feature 1', function()) {}

describe('Feature 2', function()) {}

describe('Feature 3', function()) {}

Instead:

// In spec1.ts
describe( 'Feature: Use sub-feature 1', function () {
    describe( 'Feature 1', function () {} );
} );

// In spec2.ts
describe( 'Feature: Use sub-feature 2', function () {
    describe( 'Feature 2', function () {} );
} );

Do not use modal verbs

Avoid the use of modal verbs such as can, should, could or must. Instead state the action(s) the step is expected to perform, or the end result of what should happen after this step.

Avoid:

it( 'Can log in' );

it( 'Should be able to start new post' );

Instead:

it( 'Log In' );

it( 'Start new post' );

Prefer smaller steps

Break large steps into smaller pieces for clarity and ease of debugging.

Avoid:

it( 'Log in, select home page and start a search', async function () {
    // too many things done here.
} );

Instead:

it( 'Log In', async function () {} );

it( 'Navigate to home page', async function () {} );

it( 'Search for ${string}', async function () {} );

Single responsibility function

Each function should focus on one or two key responsibilities. Avoid overloading the function to perform increasing number of tasks.

Avoid

async function publish(
    tags = '',
    saveFirst = false,
    visitAfter = false,
    setDate = ''
): Promise< void > {
    // This function is responsible for too many tasks.
    // The first clue is the long list of parameters.
    // A publishing function should publish and only publish, and do that well.
}

Instead

async function publish( { visitAfter }: { visitAfter: boolean } = {} ): Promise< void > {
    // Publish post, and possibly visit the post after publishing.
}

async function saveDraft(): Promise< void > {
    // Saves post as draft first.
}

async function applyTags( tags: string[] ): Promise< void > {
    // Applies tags.
}

async function setPublishDate( date: string ): Promise< void > {
    // Sets the publish date.
}

Destructure parameters

Use destructuring for default values as this makes calling the function explicit and avoids boolean traps.

Avoid:

constructor( selector: string, visit:boolean = true, culture:string = 'en', flow:string = '', domainFirst:boolean = false, domainFirstDomain:string = '' ) {}

// In another file

const startPage = new StartPage( selector, true, 'en', '', true, '' ).displayed();

Instead:

constructor( selector: string, { visit = true, culture = 'en', flow = '', domainFirst = false, domainFirstDomain = '' }: {visit: boolean, culture: string, flow: string, domainFirst: boolean, domainFirstDomain: string} = {} ) {}

// In another file

const startPage = new StartPage( selector, { visit: true, domainFirst: true } ).displayed();