Back to Test Automation
2025-12-077 min read

special commands (Test Automation)

Learn special commands (Test Automation) step by step with clear examples and exercises.

Title: Mastering Special Commands for Test Automation Using JavaScript (Selenium, Cypress, Playwright)

Why This Matters

Test automation is crucial in ensuring software quality and reducing manual testing efforts. Special commands are an essential feature that allows us to perform advanced actions in test scripts, making them more efficient and effective. In this lesson, we will delve deeper into various special commands for Selenium, Cypress, and Playwright using JavaScript examples.

The understanding of these special commands can help you create robust and reliable test automation scripts that cover complex scenarios and improve overall test coverage.

Prerequisites

  • Basic understanding of JavaScript programming
  • Familiarity with browser-based testing tools (Selenium, Cypress, or Playwright)
  • Knowledge of HTML/CSS selectors and web page navigation
  • Understanding of asynchronous JavaScript concepts
  • Experience with writing test scripts using one or more of the mentioned tools is beneficial but not required.

Core Concept

Special commands are additional functions that can be used in test scripts to perform operations beyond basic interactions with the user interface. These commands help automate complex tasks, improve test coverage, and reduce the amount of custom code required for specific scenarios.

Selenium, Cypress, and Playwright each have their own set of special commands, although they share some common ones due to their shared roots in WebDriver. In this lesson, we will focus on the most commonly used special commands for each tool.

Selenium Special Commands

  • executeScript: Runs JavaScript code within the current page context.
  • executeAsyncScript: Similar to executeScript, but returns a promise that resolves when the script execution is complete.
  • actions: Performs advanced user interactions such as right-clicks, double-clicks, and drag-and-drop operations.
  • webDriverWait: Waits for a specified condition to be met before continuing with the test script.
  • expectedConditions: Provides a set of predefined conditions that can be used with webDriverWait.

Cypress Special Commands

  • cy.get(selector): Finds an element on the page using a CSS selector or other locator strategies.
  • cy.contains(text): Searches for an element containing the specified text.
  • cy.wrap(element): Wraps a raw DOM element or jQuery object in a Cypress command chain.
  • cy.request: Simulates HTTP requests to verify the application's API responses.
  • cy.route: Intercepts and modifies network requests for testing purposes.

Playwright Special Commands

  • $eval: Executes JavaScript code within the context of a specific DOM element.
  • page.evaluate: Similar to Selenium's executeScript, but runs the script in the main thread rather than in the page context.
  • contextMenu: Simulates a right-click on an element and returns the context menu options.
  • page.waitForSelector: Waits for a specified selector to appear on the page before continuing with the test script.
  • page.waitForFunction: Waits for a JavaScript function to return a specific value or condition to be met before continuing with the test script.

Worked Example

Let's create a more complex test script using Selenium, Cypress, and Playwright that demonstrates the use of special commands. We will perform the following actions:

  1. Navigate to a web page
  2. Find an element by its CSS selector
  3. Perform a right-click on the found element
  4. Access the context menu options
  5. Select an option from the context menu and verify it has the expected text
  6. Verify that the web page title contains specific text after performing a search operation
  7. Simulate keyboard input using special commands for each tool: Selenium, Cypress, Playwright
// Selenium example (Expanded)
const { Builder, By, Key, until } = require('selenium-webdriver');

(async function example() {
let driver = await new Builder().forBrowser('chrome').build();
try {
await driver.get('https://example.com');
const element = await driver.findElement(By.css('#myElement'));
await driver.action({ context: 'browser' }).contextClick(element).perform();
const menuOptions = await driver.executeScript('return document.querySelectorAll("contextmenu > li")');
const optionText = (await driver.executeScript(`return document.querySelector("contextmenu > li:nth-child(2)").textContent`)).trim();
expect(optionText).toEqual('Expected Context Menu Option');
await driver.get('https://example.com/search?query=test');
const title = await driver.getTitle();
expect(title).toContain('Test Results');
await driver.findElement(By.name('search')).sendKeys('Selenium', Key.RETURN);
await driver.wait(until.titleIs('Search Results for Selenium'), 10000);
const searchResultsTitle = await driver.getTitle();
expect(searchResultsTitle).toContain('Selenium');
} catch (e) {
console.error(e);
} finally {
await driver.quit();
}
})();
// Cypress example (Expanded)
describe('Special Commands', () => {
it('Performs Right-Click and Context Menu Selection, Search Operation, and Keyboard Input Simulation', () => {
cy.visit('https://example.com');
cy.get('#myElement').rightclick();
cy.contains('Expected Context Menu Option').click();
cy.url().should('include', '/search');
cy.get('#searchInput').type('Test Automation{enter}');
cy.url().should('include', 'test-automation');
});
// Playwright example (Expanded)
const { chromium, expect } = require('playwright');

(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
const elementHandle = await page.$('#myElement');
await elementHandle.contextMenu({ force: true });
const contextMenuOptions = await page.$$eval('li', nodes => Array.from(nodes));
const optionText = await page.evaluate((nodes, expectedOption) => {
return nodes.find(node => node.textContent.trim() === expectedOption).textContent;
}, 'Expected Context Menu Option');
expect(optionText).toBe('Expected Context Menu Option');
await page.goto('https://example.com/search?query=test');
const title = await page.title();
expect(title).toContain('Test Results');
await page.fill('#searchInput', 'Selenium');
await page.keyboard.press('Enter');
await expect(page.url()).toContain('selenium');
await browser.close();
})();

Common Mistakes

  1. Forgetting to import necessary libraries or modules
  2. Using incorrect CSS selectors or XPath expressions
  3. Not handling exceptions properly when executing special commands
  4. Misunderstanding the context of special commands (e.g., using a Selenium command in Cypress)
  5. Incorrectly accessing DOM elements or properties after performing special commands
  6. Failing to wait for page loads, element visibility, or other asynchronous events before executing special commands
  7. Overusing special commands instead of writing clean and concise test scripts
  8. Not properly configuring test environments (e.g., setting up test data, user accounts, etc.)
  9. Ignoring best practices for writing maintainable and scalable test automation code

Subheadings under Common Mistakes:

  • Importing Libraries and Modules
  • CSS Selectors and XPath Expressions
  • Exception Handling
  • Contextual Awareness
  • DOM Access and Properties
  • Asynchronous Events
  • Overuse of Special Commands
  • Test Environment Configuration
  • Best Practices for Writing Test Automation Code

Practice Questions

  1. Write a test script that takes a screenshot when an element with the CSS selector .error is found on the page. (Selenium, Cypress, Playwright)
  2. Implement a test case that verifies if the web page title contains specific text after performing a search operation. (Selenium, Cypress, Playwright)
  3. Write a script to simulate keyboard input using special commands for each tool: Selenium, Cypress, Playwright.
  4. Create a test suite that logs in to a web application, navigates to a specific page, and verifies the presence of an element with text "Welcome User". (Selenium, Cypress, Playwright)
  5. Implement a test case that simulates user interactions such as scrolling, hovering over elements, and clicking on them using special commands for each tool: Selenium, Cypress, Playwright.
  6. Write a script to validate the presence of specific elements in multiple pages using Selenium, Cypress, and Playwright.
  7. Implement a test suite that performs regression testing on a web application after implementing new features or updates. (Selenium, Cypress, Playwright)

FAQ

  • Selenium is a browser-based testing framework that uses WebDriver as its core. It supports multiple programming languages and browsers.
  • Cypress is a modern JavaScript-based end-to-end testing tool designed for fast and reliable tests. It runs in the same thread as the application under test, making it more responsive.
  • Playwright is a Node.js library for web testing that provides APIs to control multiple browsers (Chromium, Firefox, WebKit) and perform end-to-end testing. It aims to provide a unified API across different browsers.

How can I handle asynchronous events in my test scripts?

  • Use the await keyword with promises returned by special commands or wait for specific conditions using expect(element).toBeVisible(), page.waitForSelector(), etc.

What are some best practices when writing test scripts with special commands?

  • Keep your tests modular and reusable, use descriptive names for functions and variables, and avoid hardcoding values whenever possible.

How do I simulate user interactions such as scrolling, hovering over elements, and clicking on them using special commands?

  • Use the scrollIntoView() method in Selenium to bring an element into view before interacting with it, and use the hover() method in Cypress and Playwright to simulate a mouse hover. For clicks, use the respective click methods for each tool.

How can I improve the performance of my test scripts using special commands?

  • Optimize your tests by reducing unnecessary wait times, minimizing the number of assertions per test, and utilizing parallel execution when possible. Additionally, consider using caching strategies to speed up test runs.

What are some common challenges faced while writing test automation scripts with special commands?

  • Test flakiness due to unpredictable application behavior, handling dynamic web pages, maintaining test data, and keeping tests up-to-date with changes in the application.

How can I ensure my test automation suite is maintainable and scalable over time?

  • Write clear and concise code, use modular functions, follow best practices for writing test automation scripts, and continuously refactor and update your test suite as needed.
special commands (Test Automation) | Test Automation | XQA Learn