### Install Testplane using npm Source: https://testplane.io/docs/v8/quickstart Installs the Testplane package globally using npm. This command initializes Testplane in your project, setting up the necessary configuration files. ```bash npm init testplane@latest YOUR_PROJECT_PATH ``` -------------------------------- ### Install Testplane browser dependencies Source: https://testplane.io/docs/v8/quickstart Installs necessary browser dependencies required for Testplane to run tests. These dependencies are downloaded automatically on the first Testplane launch if not installed beforehand. ```bash npx testplane install-deps ``` -------------------------------- ### Create a sample Testplane test Source: https://testplane.io/docs/v8/quickstart Example of a Testplane test case. This JavaScript test navigates to a GitHub repository, finds an element, and asserts its text content. ```javascript describe("github", async function () { it("should find testplane", async function ({ browser }) { await browser.url("https://github.com/gemini-testing/testplane"); const elem = await browser.$("#readme h1"); await expect(elem).toHaveText("Testplane"); }); }); ``` -------------------------------- ### Run Testplane tests Source: https://testplane.io/docs/v8/quickstart Executes all configured Testplane tests. This command runs the tests in the default mode. ```bash npx testplane ``` -------------------------------- ### Run Testplane tests in GUI mode Source: https://testplane.io/docs/v8/quickstart Launches Testplane in graphical user interface (GUI) mode, allowing for interactive test execution through a browser interface. ```bash npx testplane gui ``` -------------------------------- ### Advanced Testplane Configuration with Sets and Plugins (TypeScript) Source: https://testplane.io/docs/v8/config/main An advanced Testplane configuration example that includes retry settings for CI environments, timeouts, session and test limits, Chrome browser setup with devtools and headless mode, defining test sets for desktop, and enabling an HTML reporter plugin. ```TypeScript import type { ConfigInput } from "testplane"; export default { retry: process.env.IS_CI ? 5 : 0, httpTimeout: 60_000, sessionsPerBrowser: 5, testsPerSession: 20, browsers: { chrome: { desiredCapabilities: { browserName: "chrome", automationProtocol: "devtools", headless: true, }, }, }, sets: { desktop: { files: ["testplane-tests/**/*.testplane.(t|j)s"], browsers: ["chrome"], }, }, plugins: { "html-reporter/testplane": { enabled: true, }, }, } satisfies ConfigInput; ``` -------------------------------- ### Basic Testplane Browser Setup (TypeScript) Source: https://testplane.io/docs/v8/config/main Sets up a basic Testplane configuration by defining at least one browser, in this case, Chrome. This is the minimum required configuration to run tests with Testplane. ```TypeScript import type { ConfigInput } from "testplane"; export default { browsers: { chrome: { desiredCapabilities: { browserName: "chrome", }, }, }, } satisfies ConfigInput; ``` -------------------------------- ### Configure Testplane with a TypeScript config file Source: https://testplane.io/docs/v8/quickstart Default Testplane configuration file (testplane.config.ts). This file defines browser configurations, test sets, timeouts, and plugins like the HTML reporter. ```typescript export default { // https://testplane.io/docs/v8/guides/local-browsers/ gridUrl: "local", baseUrl: "http://localhost", pageLoadTimeout: 0, httpTimeout: 60000, testTimeout: 90000, resetCursor: false, sets: { desktop: { files: ["testplane-tests/**/*.testplane.(t|j)s"], browsers: ["chrome", "firefox"], }, }, browsers: { chrome: { headless: true, desiredCapabilities: { browserName: "chrome", }, }, firefox: { headless: true, desiredCapabilities: { browserName: "firefox", }, }, }, plugins: { "html-reporter/testplane": { // https://github.com/gemini-testing/html-reporter enabled: true, path: "testplane-report", defaultView: "all", diffMode: "3-up-scaled", }, }, }; ``` -------------------------------- ### Example Testplane CLI Command Execution Source: https://testplane.io/docs/v8/command-line Demonstrates a practical example of running Testplane tests with specific configurations. It shows how to specify a configuration file, reporter, browser, and a grep pattern. ```bash npx testplane --config ./config.js --reporter flat --browser firefox --grep name ``` -------------------------------- ### Configure Testplane devServer in TypeScript Source: https://testplane.io/docs/v8/config/dev-server Example of configuring the devServer in a Testplane configuration file (testplane.config.ts). It demonstrates setting the command to start the server, environment variables, and a readiness probe URL. ```typescript import type { ConfigInput } from "testplane"; const SERVER_PORT = 3000; export default { // ... devServer: { command: "npm run server:dev", env: { PORT: SERVER_PORT }, reuseExisting: true, readinessProbe: { url: `http://localhost:${SERVER_PORT}/health`, timeouts: { // optional waitServerTimeout: 60_000, // default value }, }, }, }; ``` -------------------------------- ### Implement Authentication using saveState and restoreState Source: https://testplane.io/docs/v8/commands/browser/restoreState Demonstrates setting up authentication using `saveState` and `restoreState` within testplane configuration. The `beforeAll` hook launches a browser, navigates to a login page, sets credentials, and saves the state. The `beforeEach` hook in the `@testplane/global-hook` plugin restores this saved state before each test, effectively logging the user in. This example requires `testplane` and `testplane/unstable` to be installed. ```javascript import { ConfigInput, WdioBrowser } from "testplane"; import { launchBrowser } from "testplane/unstable"; export default { gridUrl: "local", beforeAll: async ({ config }) => { const b = await launchBrowser(config.browsers["chrome"]!); await b.url("https://our-site.com"); await b.$("input.login").setValue("user@example.com"); await b.$("input.password").setValue("password123"); await b.saveState({ path: "./.testplane/state.json" }); await b.deleteSession(); }, sets: { /* ... */ }, browsers: { chrome: { headless: false, desiredCapabilities: { browserName: "chrome", }, }, }, plugins: { /* ... */ "@testplane/global-hook": { enabled: true, beforeEach: async ({ browser }: { browser: WdioBrowser }) => { await browser.url("https://our-site.com"); await browser.restoreState({ path: "./.testplane/state.json" }); }, }, }, } satisfies ConfigInput; ``` -------------------------------- ### Configure Testplane System Settings (TypeScript) Source: https://testplane.io/docs/v8/config/system Example configuration for the 'system' section in Testplane, demonstrating various options like debug mode, mocha timeouts, context, rejection patterns, workers, and file extensions. This configuration is written in TypeScript. ```typescript import type { ConfigInput } from "testplane"; export default { // ... system: { debug: false, mochaOpts: { timeout: 60000, }, expectOpts: { wait: 3000, interval: 100, }, ctx: { /* ... */ }, patternsOnReject: [/timeout/i, /timedout/i, /timed out/i], workers: 1, testsPerWorker: Infinity, parallelLimit: 15, fileExtensions: [".js", ".ts"], }, } satisfies ConfigInput; ``` -------------------------------- ### Example: Using Puppeteer with browser.call Source: https://testplane.io/docs/v8/commands/browser/getPuppeteer Demonstrates how to use the `getPuppeteer` command to get a Puppeteer browser instance and execute Puppeteer-specific commands asynchronously. The example shows setting geolocation and retrieving page metrics within a `browser.call` block to manage the asynchronous nature of Puppeteer operations. ```javascript it("should allow me to use Puppeteer", async ({ browser }) => { await browser.url("https://webdriver.io"); const puppeteerBrowser = await browser.getPuppeteer(); // switch to Puppeteer const metrics = await browser.call(async () => { const pages = await puppeteerBrowser.pages(); await pages[0].setGeolocation({ latitude: 59.95, longitude: 30.31667 }); return pages[0].metrics(); }); console.log(metrics.LayoutCount); // outputs: 42 }); ``` -------------------------------- ### Install Testplane Browser Dependencies Source: https://testplane.io/docs/v8/command-line Explains the `testplane install-deps` command for downloading specified browsers and necessary system packages. It covers default installation paths and how to specify custom directories using environment variables. ```bash npx testplane install-deps ``` ```bash npx testplane install-deps chrome-dark firefox-dark ``` ```bash npx testplane install-deps chrome@130 firefox@104 ``` ```bash TESTPLANE_BROWSERS_PATH=./node_modules/.testplane npx testplane install-deps ``` ```bash TESTPLANE_BROWSERS_PATH=~/.testplane npx testplane install-deps ``` -------------------------------- ### Install Testplane and Storybook Plugin Source: https://testplane.io/docs/v8/visual-testing/with-storybook Installs the Testplane testing framework and the @testplane/storybook plugin using npm. These are the initial steps to set up automated screenshot testing for Storybook components. ```bash npm init testplane@latest npm install @testplane/storybook --save-dev ``` -------------------------------- ### Install @testplane/test-repeater Source: https://testplane.io/docs/v8/plugins/testplane-test-repeater Installs the @testplane/test-repeater plugin as a development dependency using npm. ```bash npm install -D @testplane/test-repeater ``` -------------------------------- ### Install Testplane Dependencies Source: https://testplane.io/docs/v8/guides/local-browsers This command installs necessary browsers (e.g., chrome, firefox) and their corresponding web drivers. You can install all dependencies or specify individual browsers like 'chrome-dark'. This is useful for setting up a local testing environment. ```bash npx testplane install-deps ``` ```bash npm testplane install-deps chrome-dark ``` -------------------------------- ### Install url-decorator Plugin Source: https://testplane.io/docs/v8/plugins/url-decorator This snippet shows the npm command to install the url-decorator plugin as a development dependency. ```bash npm install -D url-decorator ``` -------------------------------- ### Install testplane-retry-command Plugin Source: https://testplane.io/docs/v8/plugins/testplane-retry-command Installs the testplane-retry-command plugin as a development dependency using npm. ```bash npm install -D testplane-retry-command ``` -------------------------------- ### Install @testplane/retry-progressive Plugin Source: https://testplane.io/docs/v8/plugins/testplane-retry-progressive Installs the @testplane/retry-progressive plugin as a development dependency using npm. This is the initial step before configuring the plugin in Testplane. ```bash npm install -D @testplane/retry-progressive ``` -------------------------------- ### Install testplane-chunks Plugin Source: https://testplane.io/docs/v8/plugins/testplane-chunks Installs the testplane-chunks plugin as a development dependency using npm. ```bash npm install -D testplane-chunks ``` -------------------------------- ### Install @testplane/storybook Plugin Source: https://testplane.io/docs/v8/plugins/testplane-storybook Installs the @testplane/storybook plugin as a development dependency using npm. This is the first step to integrating Storybook with Testplane. ```bash npm install @testplane/storybook --save-dev ``` -------------------------------- ### Install @testplane/global-hook Plugin Source: https://testplane.io/docs/v8/plugins/testplane-global-hook Installs the @testplane/global-hook plugin as a development dependency using npm. ```bash npm install -D @testplane/global-hook ``` -------------------------------- ### Example: Minify Reference Screenshots on Update Source: https://testplane.io/docs/v8/reference/testplane-events An implementation example for the UPDATE_REFERENCE event, showing how to automatically compress reference screenshots using a minifier plugin. This optimizes storage and potentially improves loading times for reference images. ```javascript const parseConfig = require("./config"); const Minifier = require("./minifier"); module.exports = (testplane, opts) => { const pluginConfig = parseConfig(opts); if (!pluginConfig.enabled) { // plugin is disabled – exit return; } const minifier = Minifier.create(pluginConfig); testplane.on(testplane.events.UPDATE_REFERENCE, ({ refImg }) => { minifier.minify(refImg.path); }); }; ``` -------------------------------- ### Install retry-limiter Plugin Source: https://testplane.io/docs/v8/plugins/retry-limiter Installs the retry-limiter plugin as a development dependency using npm. ```bash npm install -D retry-limiter ``` -------------------------------- ### Example: Using getMeta with setMeta - JavaScript Source: https://testplane.io/docs/v8/commands/browser/getMeta Demonstrates how to use getMeta in conjunction with setMeta to store and retrieve test metadata. It shows fetching individual values and the entire metadata object. This example is specific to the Testplane environment. ```javascript it("should get meta info of test", async ({ browser }) => { await browser.setMeta("foo", "bar"); await browser.url("/foo/bar?baz=qux"); const val = await browser.getMeta("foo"); console.log(val); // outputs: bar const url = await browser.getMeta("url"); console.log(url); // outputs: /foo/bar?baz=qux const meta = await browser.getMeta(); console.log(meta); // outputs: {foo: 'bar', url: '/foo/bar?baz=qux'} }); ``` -------------------------------- ### Install html-reporter Package Source: https://testplane.io/docs/v8/html-reporter/overview This snippet shows how to install the html-reporter package as a development dependency using npm. This is the first step to integrating the reporter into your testing workflow. ```bash npm i -D html-reporter ``` -------------------------------- ### Install Testplane and React Dependencies Source: https://testplane.io/docs/v8/guides/component-testing Installs Testplane and necessary development dependencies for React component testing using npm. Includes Testplane itself, Vite, and React testing utilities. ```bash npm init testplane@latest npm i vite @vitejs/plugin-react @testing-library/react --save-dev npm i react --save ``` -------------------------------- ### Install hermione-browser-version-changer Plugin Source: https://testplane.io/docs/v8/plugins/hermione-browser-version-changer Installs the hermione-browser-version-changer plugin as a development dependency using npm. ```bash npm install -D hermione-browser-version-changer ``` -------------------------------- ### Testplane CLI Help and Usage Source: https://testplane.io/docs/v8/command-line Displays the main help information for the `testplane` command, outlining available options and their descriptions. This is the primary entry point for understanding CLI functionality. ```bash > testplane --help Usage: testplane [options] [command] [paths...] Run tests Options: -V, --version output the version number -c, --config path to configuration file -b, --browser run tests only in specified browser -s, --set run tests only in the specified set -r, --require require module --grep run only tests matching the pattern --reporter test reporters --update-refs update screenshot references or gather them if they do not exist ("assertView" command) --inspect [inspect] nodejs inspector on [=[host:]port] --inspect-brk [inspect-brk] nodejs inspector with break at the start --repl [type] run one test, call `browser.switchToRepl` in test code to open repl interface (default: false) --repl-before-test [type] open repl interface before test run (default: false) --repl-on-fail [type] open repl interface on test fail only (default: false) --devtools switches the browser to the devtools mode with using CDP protocol --local use automatically downloaded browsers and drivers, provided by Testplane --keep-browser do not close browser session after test completion --keep-browser-on-fail do not close browser session when test fails -h, --help output usage information ``` -------------------------------- ### Get Accessibility Tree Snapshot using Testplane and Puppeteer Source: https://testplane.io/docs/v8/guides/how-to-check-accessibility This example demonstrates how to obtain the accessibility tree snapshot of a webpage using Testplane and Puppeteer. It involves getting a Puppeteer instance, navigating to a URL, and then capturing the accessibility snapshot. The snapshot is then logged to the console. ```javascript it("should get accessibility tree of yandex.ru", async function ({ browser }) { // Get puppeteer instance const puppeteer = await browser.getPuppeteer(); // Get the first open page (considering it to be currently active) const [page] = await puppeteer.pages(); await browser.url("https://yandex.ru"); // Get the current state of the accessibility tree const snapshot = await page.accessibility.snapshot(); console.log("snapshot:", JSON.stringify(snapshot, null, 4)); }); ``` -------------------------------- ### Get Text of Menu Link using $$ in JavaScript Source: https://testplane.io/docs/v8/commands/element/_dollardollar An example showing how to use the $$ command to retrieve the text of a specific menu link within a list. It first selects the parent element with ID 'menu', then targets the third list item and its anchor tag to get the text. ```javascript it("should get text of a menu link", async ({ browser }) => { const text = await browser.$("#menu"); console.log(await text.$$("li")[2].$("a").getText()); // outputs: "API" }); ``` -------------------------------- ### Get Element Text using $ and $$ Source: https://testplane.io/docs/v8/commands/browser/_dollar This example demonstrates how to retrieve the text of a specific menu link using the `$` and `$$` commands. It first selects the menu element and then navigates down the DOM to the desired link. ```javascript it("should get text of a menu link", async ({ browser }) => { const text = await browser.$("#menu"); console.log(await text.$$("li")[2].$("a").getText()); // outputs: "API" }); it("should get text of a menu link - JS Function", async ({ browser }) => { const text = await browser.$(function () { // Arrow function cannot be used here. // This is Window – https://developer.mozilla.org/en-US/docs/Web/API/Window // // TypeScript users can do something like: // return (this as Window).document.querySelector('#menu') return this.document.querySelector("#menu"); // Element }); console.log(await text.$$("li")[2].$("a").getText()); // outputs: "API" }); ``` -------------------------------- ### Demonstrate respondOnce Command Usage Source: https://testplane.io/docs/v8/commands/mock/respondOnce This example demonstrates how to use the respondOnce command to mock responses for a to-do list application. It shows calling respondOnce multiple times with different data and then verifying the application displays the mocked data sequentially. After exhausting mocks, it shows fetching the original resource response. ```javascript async function getToDos(browser) { await browser.$("#todo-list li").waitForExist(); const todoElements = await browser.$$("#todo-list li"); return Promise.all(todoElements.map(el => el.getText())); } it("should demonstrate the respondOnce command", async ({ browser }) => { const mock = await browser.mock("https://todo-backend-express-knex.herokuapp.com/", { method: "get", }); mock.respondOnce([ { title: "3", }, { title: "2", }, { title: "1", }, ]); mock.respondOnce([ { title: "2", }, { title: "1", }, ]); mock.respondOnce([ { title: "1", }, ]); await browser.url( "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", ); console.log(await getToDos(browser)); // outputs: [ '3', '2', '1' ] await browser.url( "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", ); console.log(await getToDos(browser)); // outputs: [ '2', '1' ] await browser.url( "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", ); console.log(await getToDos(browser)); // outputs: [ '1' ] await browser.url( "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", ); console.log(await getToDos(browser)); // outputs: the actual resource response }); ``` -------------------------------- ### Get Help for Testplane CLI Source: https://testplane.io/docs/v8/command-line Displays help information for the Testplane CLI, including available commands and options. It also shows how plugins can extend functionality, such as the html-reporter adding a 'gui' command. ```bash testplane list-tests --help ``` -------------------------------- ### Execute switchToRepl Command - JavaScript Source: https://testplane.io/docs/v8/commands/browser/switchToRepl This example demonstrates the basic usage of the `switchToRepl` command within a Testplane test. It shows how to initiate the REPL mode and logs messages before and after its execution. The REPL allows for interactive debugging in the terminal. ```javascript it("test", async ({ browser }) => { console.log("before open repl"); await browser.switchToRepl(); console.log("after open repl"); }); ``` -------------------------------- ### Set Mocha Timeout in Testplane (TypeScript) Source: https://testplane.io/docs/v8/config/system Configures the mocha timeout for tests within the Testplane 'system' settings. This example specifies a timeout of 60000 milliseconds using TypeScript. ```typescript import type { ConfigInput } from "testplane"; export default { // ... system: { mochaOpts: { timeout: 60000, }, }, } satisfies ConfigInput; ``` -------------------------------- ### Help Option Source: https://testplane.io/docs/v8/command-line Prints information about available options and commands, including those added by plugins. ```APIDOC ## Help Option ### Description Prints out information about options and commands. Testplane Plugins can add their own commands and options. For example, `html-reporter` adds the `gui` command. ### Example Usage ```bash testplane --help ``` ``` -------------------------------- ### Initialize Testplane Instance Source: https://testplane.io/docs/v8/reference/testplane-api Provides an example of how to initialize the Testplane instance using the `testplane.init()` command. This command is responsible for loading plugins and setting up the Testplane environment. ```javascript await testplane.init(); ``` -------------------------------- ### Implement testplane-dev-server Plugin Source: https://testplane.io/docs/v8/reference/testplane-events This JavaScript code implements the testplane-dev-server plugin. It hooks into the CLI event to add a --dev-server option and the INIT event to conditionally start an HTTP server. The plugin requires the 'http' module and a local 'config' module. It serves 'Hello, World!' on port 3000. ```javascript const http = require("http"); const parseConfig = require("./config"); module.exports = (testplane, opts) => { const pluginConfig = parseConfig(opts); if (!pluginConfig.enabled || testplane.isWorker()) { // either the plugin is disabled, or we are in the worker context – exit return; } let program; testplane.on(testplane.events.CLI, cli => { // need to save a reference to the commander instance (https://github.com/tj/commander.js), // to later check for the option program = cli; // add the --dev-server option to testplane, // so the user can explicitly specify when to start the dev server cli.option("--dev-server", "run dev-server"); }); testplane.on(testplane.events.INIT, () => { // the dev server can be started either by specifying the --dev-server option // when launching testplane, or in the plugin settings const devServer = (program && program.devServer) || pluginConfig.devServer; if (!devServer) { // if the dev server doesn't need to be started – exit return; } // content served by the dev server const content = "

Hello, World!

"; // create the server and start listening on port 3000 http.createServer((req, res) => res.end(content)).listen(3000); // at http://localhost:3000/index.html, the content will be:

Hello, World!

}); }; ``` -------------------------------- ### Manage SSH Tunnel with RUNNER_START and RUNNER_END Events Source: https://testplane.io/docs/v8/reference/testplane-events This example demonstrates how to open an SSH tunnel when the test runner starts and close it when the runner finishes using the RUNNER_START and RUNNER_END events. It relies on the './config' and './lib/tunnel' modules for configuration parsing and tunnel management. ```javascript const parseConfig = require("./config"); const Tunnel = require("./lib/tunnel"); module.exports = (testplane, opts) => { const pluginConfig = parseConfig(opts); if (!pluginConfig.enabled) { // plugin is disabled – exit return; } // plugin config defines tunnel parameters: // host, ports, localport, retries, etc. const tunnel = Tunnel.create(testplane.config, pluginConfig); testplane.on(testplane.events.RUNNER_START, () => tunnel.open()); testplane.on(testplane.events.RUNNER_END, () => tunnel.close()); }; ``` -------------------------------- ### Initialize Runner with RUNNER_START Event Source: https://testplane.io/docs/v8/reference/testplane-events The RUNNER_START event is triggered asynchronously after Testplane workers are initialized but before tests begin execution. The handler receives the runner instance, allowing for pre-test setup or subscription to runner events. Tests will not start until the Promise returned by the handler resolves. ```javascript testplane.on(testplane.events.RUNNER_START, async runner => { console.info("Processing RUNNER_START event..."); }); ``` -------------------------------- ### Run Tests and Serve Report Source: https://testplane.io/docs/v8/html-reporter/overview Commands to execute tests using npm and then serve the generated html-report locally using the 'serve' command. This allows viewing the test results in a browser. ```bash npm test npx serve html-report ``` -------------------------------- ### getText Example: Extracting Text from Table Cells Source: https://testplane.io/docs/v8/commands/element/getText Shows how to use the getText command to extract text content from a specific cell within an HTML table. This involves selecting the table, rows, and then the desired cell to get its text. ```javascript it("get content from table cell", async ({ browser }) => { await browser.url("http://the-internet.herokuapp.com/tables"); const rows = await browser.$$('#table1 tr'); const columns = await rows[1].$$("td"); // get columns of the 2nd row console.log(await columns[2].getText()); // get text from the 3rd column }); ``` -------------------------------- ### Running REPL with Context - Shell Source: https://testplane.io/docs/v8/commands/browser/switchToRepl This example demonstrates how to launch Testplane with the `--repl` flag and a specific grep pattern to target a test that utilizes context in `switchToRepl`. It then shows interacting with the context variable `counter` within the REPL. ```shell npx testplane --repl --grep "test" -b "chrome" > console.log("counter:", counter); counter: 1 ``` -------------------------------- ### Modify API Responses with Mock in Testplane Source: https://testplane.io/docs/v8/commands/browser/mock Shows how to modify API responses using the 'mock' command and its 'respond' method. This example demonstrates mocking a GET request to '/todos' and then defining a custom response, including altering the status code and response headers. ```javascript it("should modify API responses", async ({ browser }) => { // filter by method const todoMock = await browser.mock("**" + "/todos", { method: "get", }); // mock the response of the endpoint with predefined fixture todoMock.respond([ { title: "Injected Todo", order: null, completed: false, url: "http://todo-backend-express-knex.herokuapp.com/916", }, ]); // respond with a different status code or header todoMock.respond( [ { title: "Injected Todo", order: null, completed: false, url: "http://todo-backend-express-knex.herokuapp.com/916", }, ], { statusCode: 404, headers: { "x-custom-header": "foobar", }, }, ); }); ``` -------------------------------- ### Express Router Setup in middleware.js (JavaScript) Source: https://testplane.io/docs/v8/html-reporter/html-reporter-plugins This JavaScript code snippet demonstrates how to set up an Express router within a plugin. It exports a function that accepts a pluginRouter and defines a GET route '/plugin-route'. This is intended to be connected to the main application's router at '/plugin-routes/:PluginName/'. ```javascript module.exports = function (pluginRouter) { pluginRouter.get("/plugin-route", function (req, res) { // "route" implementation }); }; ``` -------------------------------- ### Run Tests with Testplane Source: https://testplane.io/docs/v8/reference/testplane-api Illustrates the usage of the `testplane.run()` command to execute tests. It shows an example call and details the optional parameters available for configuring the test run, such as reporters, browsers, and filters. ```javascript const success = await testplane.run(testPaths, options); ``` -------------------------------- ### Help Command Source: https://testplane.io/docs/v8/command-line Prints out information about available options and commands for Testplane, including potential commands added by plugins. ```APIDOC ## help ### Description Displays help information for Testplane commands and options. This includes core Testplane functionality and any custom commands or options provided by installed plugins. ### Method CLI Command ### Endpoint N/A (CLI Command) ### Parameters N/A ### Request Example ```bash testplane list-tests --help ``` ### Response Outputs usage information for the command, detailing available options and their descriptions. ``` -------------------------------- ### Get Next Sibling Element using JavaScript Source: https://testplane.io/docs/v8/commands/element/nextElement Demonstrates how to select the next sibling element using the nextElement command. It takes a selector as input and returns the next sibling element. This example requires the browser object and assumes a basic HTML structure with sibling elements. ```javascript it("should get text from next sibling element", async ({ browser }) => { const elem = await browser.$$("p"); const nextElement = await elem[1].nextElement(); console.log(await nextElement.getText()); // outputs: "Sibling Three" }); ``` -------------------------------- ### List Tests with Custom Configuration and Format Source: https://testplane.io/docs/v8/command-line An example demonstrating how to use the `list-tests` command with several options: specifying a configuration file, filtering by browser, applying a grep pattern, and setting the output format to 'tree'. ```bash npx testplane list-tests --config ./config.js --browser firefox --grep name --formatter tree ``` -------------------------------- ### Get Text of a Menu Link Using JS Function - WebdriverIO Source: https://testplane.io/docs/v8/commands/element/_dollar This example demonstrates how to select a specific menu link using a JavaScript function as a selector within the `browser.$` command. It navigates down the DOM tree by chaining `$$` and `$` to find the third list item and then the anchor tag within it, finally retrieving its text. ```javascript it("should get text of a menu link - JS Function", async ({ browser }) => { const text = await browser.$("#menu"); console.log( await text .$$("li")[2] .$(function () { // Arrow function cannot be used here. // This is Element – https://developer.mozilla.org/en-US/docs/Web/API/Element // in this specific example – this is HTMLLIElement // // TypeScript users can do something like: // return (this as Element).querySelector('a') return this.querySelector("a"); // Element }) .getText() ); // outputs: "API" }); ``` -------------------------------- ### Configure Local Chrome Testing with DevTools Protocol Source: https://testplane.io/docs/v8/migrations/how-to-upgrade-hermione-to-4 This configuration example shows how to set up Chrome for local testing using the DevTools Protocol in Hermione. By setting the `automationProtocol` to `'devtools'`, you simplify the local testing setup, eliminating the need for `selenium-standalone` and a `gridUrl`. This configuration is specific to the Chrome browser. ```javascript // hermione.conf.js module.exports = { browsers: { chrome: { automationProtocol: 'devtools', desiredCapabilities: { // ... } } }, // other hermione settings... }; ``` -------------------------------- ### Disable Scrollbars on Session Start with Chrome DevTools Protocol (JavaScript) Source: https://testplane.io/docs/v8/reference/testplane-events This example shows how to subscribe to the SESSION_START event in Testplane. When triggered, it disables scrollbars in specified browsers using the Chrome DevTools Protocol. It parses configuration, checks if the plugin is enabled and if the current browser is in the allowed list, then connects to the browser via CDP to hide scrollbars. ```javascript const parseConfig = require("./config"); const DevTools = require("./dev-tools"); module.exports = (testplane, opts) => { const pluginConfig = parseConfig(opts); if (!pluginConfig.enabled) { // plugin is disabled – exit return; } testplane.on(testplane.events.SESSION_START, async (browser, { browserId, sessionId }) => { if (!pluginConfig.browsers.includes(browserId)) { // the browser is not in the list of browsers for which scrollbars can be disabled // using the Chrome DevTools Protocol (CDP) – exit return; } const gridUrl = testplane.config.forBrowser(browserId).gridUrl; // pluginConfig.browserWSEndpoint defines a function that should return the URL // for working with the browser via CDP. To allow the function to compute the URL, // the function receives the session identifier and the grid URL const browserWSEndpoint = pluginConfig.browserWSEndpoint({ sessionId, gridUrl }); const devtools = await DevTools.create({ browserWSEndpoint }); devtools.setScrollbarsHiddenOnNewPage(); await devtools.hideScrollbarsOnActivePages(); }); }; ``` -------------------------------- ### Example: Radio Buttons for Base URL Customization Source: https://testplane.io/docs/v8/html-reporter/html-reporter-custom-gui Demonstrates how to use radio buttons within the `customGui` configuration to allow users to change the base URL in GUI mode. It includes setup for controls, initialization logic to set the active button based on the current base URL, and an action to update the configuration when a button is clicked. ```javascript customGui: { 'some-meaningful-name-of-section': [ { type: 'radiobutton', controls: [ { label: 'Dev', value: 'http://localhost/development/' }, { label: 'Prod', value: 'http://localhost/production/' } ], initialize: async ({ testplane, ctx }) => { const { config } = testplane; const browserIds = config.getBrowserIds(); if (browserIds.length) { const { baseUrl } = config.forBrowser(browserIds[0]); ctx.controls.forEach((control) => { control.active = (baseUrl === control.value); }); } }, action: async ({ testplane, ctx, control }) => { const { config } = testplane; config .getBrowserIds() .forEach((browserId) => { config.forBrowser(browserId).baseUrl = control.value; }); } } ] } ``` -------------------------------- ### Start Express Server and Listen on Port (TypeScript) Source: https://testplane.io/docs/v8/html-reporter/static-accepter This code snippet sets up an Express server to listen on a specified port. It reads the port from the environment variable `PORT` or defaults to 3000. A confirmation message is logged to the console once the server starts. This is the entry point for the application. ```typescript const port = process.env.PORT ?? 3000; app.listen(port, () => { console.log(`Static accepter listening on :${port}`); }); ``` -------------------------------- ### Example: Aborting Mock Once in Test (JavaScript) Source: https://testplane.io/docs/v8/commands/mock/abortOnce An example test case using `abortOnce` to abort a mock request once. It navigates to a URL, aborts the mock, and then navigates again to verify the behavior. This example uses `browser.mock` and `mock.abortOnce`. ```javascript it("should block mock only once", async ({ browser }) => { const mock = await browser.mock("https://webdriver.io"); mock.abortOnce("Failed"); await browser .url("https://webdriver.io") // catch exception as the request to the page will fail .catch(() => console.log('Failed to get the page "https://webdriver.io"')); await browser.url("https://webdriver.io"); console.log(await browser.getTitle()); // will output: "WebdriverIO · Next-gen browser and mobile automation test framework for Node.js" }); ``` -------------------------------- ### Testplane GitHub Action with Comprehensive Parameters Source: https://testplane.io/docs/v8/guides/how-to-run-on-github This example demonstrates the 'gemini-testing/gh-actions-testplane' GitHub Action configured with various parameters. It showcases how to specify the working directory, package manager, HTML report path, custom config file, Storybook integration, test sets, browsers, and grep expressions for a more targeted test run. ```yaml - name: Run Comprehensive Testplane Suite id: testplane uses: gemini-testing/gh-actions-testplane@v1 with: cwd: "projects/my-project-name" # Specify project path (for monorepos) package-manager: "yarn" # Use yarn instead of npm html-report-prefix: "reports/testplane" # Save reports to existing reports directory (for preserving reports on gh-pages) config-path: "configs/testplane.conf.js" # Use custom config path storybook: "true" # Run tests from `@testplane/storybook` plugin set: "smoke,regression" # Run only selected test sets browser: "linux-chrome,linux-firefox" # Run tests in two browsers only grep: "Login" # Run only tests containing 'Login' in their name ``` -------------------------------- ### REPL Interaction Example - Shell Source: https://testplane.io/docs/v8/commands/browser/switchToRepl This snippet illustrates how to interact with the REPL interface after `switchToRepl` has been invoked. It shows executing a command like `await browser.getUrl()` directly in the terminal and observing the output. ```shell > await browser.getUrl(); about:blank ``` -------------------------------- ### Initialize Testplane API Source: https://testplane.io/docs/v8/reference/testplane-api Initializes the Testplane instance and loads all plugins. ```APIDOC ## init ### Description Initializes the testplane instance, loads all plugins, etc. ### Method `await testplane.init();` ### Example Call ```javascript await testplane.init(); ``` ``` -------------------------------- ### Install stat-reporter Plugin Source: https://testplane.io/docs/v8/plugins/stat-reporter This command installs the stat-reporter plugin as a development dependency for your Testplane project using npm. ```bash npm install -D stat-reporter ```