### Install Taiko Dependencies Source: https://github.com/getgauge/taiko/blob/master/tests/functional-tests/README.md Run this command to install necessary dependencies for Taiko. ```bash npm install ``` -------------------------------- ### Basic Plugin Usage Example Source: https://github.com/getgauge/taiko/wiki/Taiko-Plugin This example demonstrates how to use a plugin like 'screencast' which is made available after requiring Taiko and potentially loading plugins via environment variables or dependencies. Ensure the plugin is correctly initialized. ```javascript const { openBrowser, goto, write, press, closeBrowser , inputField, into, screencast} = require('taiko'); (async () => { try { await openBrowser(); await screencast.start(); await goto('google.com'); await write('taiko', into(inputField())); await press('Enter'); } catch (e) { console.log(e); } finally { await closeBrowser(); await screencast.stop(); } })(); ``` -------------------------------- ### Serve Taiko Documentation Locally Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/README.md Use this command to start a local development server for previewing the Taiko documentation. ```bash npm run doc:serve ``` -------------------------------- ### Install Unreleased Taiko from GitHub Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/installing.md Install Taiko directly from its GitHub repository to experiment with unreleased versions and experimental features. ```bash npx https://github.com/getgauge/taiko ``` ```bash npm install -g https://github.com/getgauge/taiko ``` ```bash npm install -D https://github.com/getgauge/taiko ``` -------------------------------- ### Example Usage of Screencast Plugin Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/writing_plugins.md This example demonstrates how to use the screencast plugin to record a GIF of the script execution. Ensure the screencast plugin is loaded. ```javascript const { openBrowser, goto, write, press, closeBrowser, into, textBox, screencast} = require('taiko'); (async () => { try { await openBrowser(); await screencast.startScreencast("output.gif"); await goto('google.com'); await write('taiko', into(textBox())); await press('Enter'); } catch (e) { console.log(e); } finally { await screencast.stopScreencast(); await closeBrowser(); } })(); ``` -------------------------------- ### Launch Test Documentation Generation Source: https://github.com/getgauge/taiko/blob/master/tests/docs-tests/README.md Run this command from the project root directory to start the documentation testing process. ```bash npm run test-docs ``` -------------------------------- ### Install Mocha and Taiko for Testing Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Install Mocha as a development dependency and Taiko. These commands add the necessary packages to your project. ```bash npm i -D mocha npm i -D taiko ``` -------------------------------- ### Global Installation of Taiko Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/installing.md Install the `taiko` command globally on your system for command-line access. ```bash npm install -g taiko ``` -------------------------------- ### Install Gauge CLI Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Install the Gauge command-line interface globally using npm. This is the first step to integrating Taiko with Gauge. ```bash npm install -g @getgauge/cli ``` -------------------------------- ### Verify Taiko Installation Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/installing.md Check your Taiko installation by running the version command. This confirms the installed Taiko and Chromium versions. ```bash taiko --version ``` -------------------------------- ### Initialize Taiko Project with Gauge (JavaScript) Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/README.md Install the Gauge CLI and initialize a new JavaScript project with Taiko integration. This sets up the basic structure for acceptance tests. ```bash npm install @getgauge/cli gauge init js ``` -------------------------------- ### Quick Install Taiko Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/installing.md Use `npx` for quick experimentation or to automate a web page. This command downloads and launches the Chromium browser with Taiko's recorder. ```bash npx taiko ``` -------------------------------- ### Install Jest and Taiko for Testing Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Install Jest as a development dependency and Taiko. These commands add the necessary packages to your project for Jest-based testing. ```bash npm i -D jest npm i -D taiko ``` -------------------------------- ### View Specific API Details in Taiko REPL Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/README.md Shows detailed information and examples for a specific Taiko API command in the REPL. ```bash >.api openBrowser Launches a browser with a tab. The browser will be closed when the parent node.js process is closed. Example: openBrowser() openBrowser({ headless: false }) openBrowser({args:['--window-size=1440,900']}) ``` -------------------------------- ### Initialize Taiko Project with Gauge CLI Source: https://github.com/getgauge/taiko/blob/master/README.md Install the Gauge CLI using npm and initialize a new JavaScript-based Taiko project. This sets up the necessary files and configurations for Gauge and Taiko. ```bash $ npm install @getgauge/cli $ gauge init js ``` -------------------------------- ### Install Chromium and Configure Taiko for Raspberry Pi Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/frequently_asked_questions.md Install the chromium-browser package and configure Taiko to use it by setting TAIKO_SKIP_CHROMIUM_DOWNLOAD and TAIKO_BROWSER_PATH environment variables. ```bash apt install chromium-browser TAIKO_SKIP_CHROMIUM_DOWNLOAD=true npm install -g taiko `TAIKO_BROWSER_PATH=$(which chromium-browser)` taiko ``` -------------------------------- ### Install Taiko and Chromium Source: https://github.com/getgauge/taiko/blob/master/README.md Install Taiko globally using npm. This command also installs the latest version of the Chromium browser, which is required for Taiko to function. ```bash $ npm install -g taiko ``` -------------------------------- ### Install Taiko Plugin Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/plugins.md Install a Taiko plugin into your project using npm. This command adds the specified plugin to your project's dependencies. ```bash npm install taiko-diagnostics ``` -------------------------------- ### Initialize Taiko Project with Gauge (TypeScript) Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/README.md Install the Gauge CLI and initialize a new TypeScript project with Taiko integration using `gauge-ts`. This is for setting up end-to-end tests in TypeScript. ```bash npm install @getgauge/cli gauge init ts ``` -------------------------------- ### Install Taiko Skipping Chromium Download Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/installing.md Set the `TAIKO_SKIP_CHROMIUM_DOWNLOAD` environment variable to `true` to install Taiko without downloading the Chromium browser. ```bash TAIKO_SKIP_CHROMIUM_DOWNLOAD=true npx taiko ``` -------------------------------- ### Local Installation of Taiko Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/installing.md Add Taiko as a development dependency to your Node.js project. This installs Taiko locally within your project's `node_modules` folder. ```bash npm install -D taiko ``` -------------------------------- ### Explore Taiko API Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/record_and_run_tests.md Use the `.api` command in the Taiko REPL to list available commands or get details about a specific API. ```bash > .api ``` ```bash > .api click ``` -------------------------------- ### Install Taiko Globally as Root User Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/installing.md When installing Taiko globally as a root user, use `--unsafe-perm --allow-root` flags with `npm` to avoid permission errors. ```bash npm install -g taiko --unsafe-perm --allow-root ``` -------------------------------- ### Interactive Taiko REPL Commands Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/overview.md Examples of commands used within the Taiko REPL (Read-Eval-Print Loop) for browser automation. ```javascript > openBrowser() ``` ```javascript > goto("google.com") ``` ```javascript > write("taiko test automation") ``` ```javascript > click("Google Search") ``` -------------------------------- ### Prompting User Input with JavaScript Source: https://github.com/getgauge/taiko/blob/master/tests/functional-tests/specs/data/HTMLElements.html Demonstrates how to use the JavaScript prompt function to get user input. The input can then be used to update the DOM. ```javascript function myFunction() { var person = prompt("Please enter your name", "Harry Potter"); if (person != null) { document.getElementById("demo").innerHTML = "Hello " + person + "! How are you today?"; } } ``` -------------------------------- ### Calculate Proximity Distances Source: https://github.com/getgauge/taiko/wiki/Taiko's-Proximity-Selector This example demonstrates how to calculate proximity distances for elements relative to others using `near()` and `toRightOf()`. It shows the step-by-step calculation of `distanceBetweenAllReference` for two elements, A(1) and A(2), based on their proximity to elements C and B. ```javascript A = [A(1), A(2)] matchingAWithProximityToArgs = [] A(1): distanceBetweenAllReference = 0; 1] near(C): C = [C(1),C(2)] A(1) near C(1) === true => closestC = C(1) A(1) near C(2) === false distanceBetweenAllReference = 1 (A(1) -> closestC distance) 2] toRightOf(B): B = [B] A(1) toRightOf B === true => closestB = B distanceBetweenAllReference += closestB = 1+2 = 3 matchingAWithProximityToArgs = [ {A(1), 3} ] A(2): distanceBetweenAllReference = 0; 1] near(C): C = [C(1),C(2)] A(2) near C(1) === false A(2) near C(2) === true => closestC = C(2) distanceBetweenAllReference = 1 (A(2) -> closestC distance) 2] toRightOf(B): B = [B] A(1) toRightOf B === true => closestB = B distanceBetweenAllReference += closestB = 1+5 = 6 matchingAWithProximityToArgs = [ {A(1), 3}, {A(2),6} ] sortByTotalDistance(matchingAWithProximityToArgs) ``` -------------------------------- ### Run Specific Taiko Spec File Source: https://github.com/getgauge/taiko/blob/master/tests/functional-tests/README.md Use the --spec option to run a particular spec file. You can also specify a line number to start from. ```bash npm run --spec=specs/browserActions.spec ``` ```bash npm run --spec=specs/browserActions.spec:23 ``` -------------------------------- ### Taiko Script with Mocha Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Example of a Taiko script written within a Mocha test suite. It includes `before` and `after` hooks for browser management and a test case for Google search. ```javascript const { openBrowser, goto, closeBrowser, write, press } = require('taiko'); describe('Taiko with Mocha', () => { before(async() => { await openBrowser(); }); describe('Google search', async() => { it('should use Taiko to search google', async() => { await goto('google.com'); await write('flying foxes'); await press('Enter'); }); }); after(async() => { await closeBrowser(); }); }); ``` -------------------------------- ### Configure Plugin with Gauge Runner Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/plugins.md Set the TAIKO_PLUGIN environment variable to enable plugins when running tests with Gauge. This example shows how to set the variable in bash or zsh. ```bash TAIKO_PLUGIN=diagnostics gauge run specs ``` -------------------------------- ### Custom Assertion with Node.js assert.equal Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/assertions.md Implement custom assertions using Node.js's 'assert' module. This example checks if a button's text content matches an expected value. ```javascript const { openBrowser, goto, click, closeBrowser } = require('taiko'); const assert = require('assert').strict; (async () => { await openBrowser(); await goto("google.com"); assert.equal(button({name: 'btnK'}).text(), 'Google Search'); closeBrowser(); })(); ``` -------------------------------- ### Taiko Script with Jest Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Example of a Taiko script written within a Jest test suite. It uses `beforeAll` and `afterAll` hooks for browser management and a test case for Google search. ```javascript const { openBrowser, goto, closeBrowser, write, press } = require('taiko'); describe('Taiko with Jest', () => { beforeAll(async() => { await openBrowser(); }); describe('Google search', () => { test('should use Taiko to search google', async() => { await goto('google.com'); await write('flying foxes'); await press('Enter'); }); }); afterAll(async() => { await closeBrowser(); }); }); ``` -------------------------------- ### Proximity Selector Example: Simple Source: https://github.com/getgauge/taiko/wiki/Taiko's-Proximity-Selector Demonstrates a simple proximity selector where 'taiko' is found near 'automation'. This is useful for finding an element relative to another when their exact positions might vary. ```javascript text('taiko', near('automation')) ``` -------------------------------- ### Proximity Selector Example: Combination Source: https://github.com/getgauge/taiko/wiki/Taiko's-Proximity-Selector Shows a combined proximity selector, finding 'taiko' near 'automation' and above 'browser'. This allows for more specific element targeting by combining multiple proximity conditions. ```javascript text('taiko', near('automation'), above('browser')) ``` -------------------------------- ### Iterate through all list items Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/working_with_element_lists.md Use `listItem({ selector: 'value' }).elements()` to get an array of all `ElementWrapper` objects that match the selector. You can then loop through this array to process each element, for example, by logging their text content. ```javascript /* Prints Apple Orange Melon Pear */ var fruits = await listItem({class: "fruit"}).elements(); for (fruit of fruits) { console.log(await fruit.text()); } ``` -------------------------------- ### Set TAIKO_BROWSER_PATH for Firefox Nightly Source: https://github.com/getgauge/taiko/blob/master/README.md To use Taiko with Firefox Nightly, download and install the browser, then set the `TAIKO_BROWSER_PATH` environment variable to the executable's path. This example shows setting the path for macOS. ```bash TAIKO_BROWSER_PATH="/Applications/Firefoxnightly.app/Contents/MacOS/firefox" taiko ``` -------------------------------- ### Build Taiko Documentation Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/README.md Run this command to build the static documentation website for Taiko. ```bash npm run doc ``` -------------------------------- ### Initialize npm Project for Mocha Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Initialize a new npm project. This command creates a package.json file if one does not exist. ```bash npm init -y ``` -------------------------------- ### Open Browser with Taiko REPL Source: https://github.com/getgauge/taiko/blob/master/README.md Opens a Chromium browser instance from the Taiko REPL. ```bash > openBrowser() ``` -------------------------------- ### View API Documentation in Taiko REPL Source: https://github.com/getgauge/taiko/blob/master/README.md Displays a list of available Taiko API commands within the REPL. ```bash > .api ``` -------------------------------- ### Load Taiko Session from File Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/record_and_run_tests.md Use the `--load` option when launching Taiko to load and execute commands from a specified JavaScript file, then enter the REPL. ```bash npx taiko --load googlesearch.js ``` -------------------------------- ### Launch Taiko REPL Source: https://github.com/getgauge/taiko/blob/master/README.md Launches the Taiko REPL in the terminal. Use '.api' for help and '.exit' to quit. ```bash $ taiko Version: 1.4.0 (Chromium: 126.0.6468.0) Type .api for help and .exit to quit > ``` -------------------------------- ### Launch Chrome in Headless Mode with Sandbox Configuration Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/frequently_asked_questions.md Configure kernel settings for user namespace cloning or use a setuid sandbox for running Taiko in headless environments like Docker. Alternatively, disable sandboxing with specific arguments if necessary. ```bash sudo sysctl -w kernel.unprivileged_userns_clone=1 ``` ```javascript await openBrowser({args: ['--no-sandbox', '--disable-setuid-sandbox']}); ``` -------------------------------- ### Initialize Gauge Project Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Initialize a new JavaScript project with Gauge. This command sets up the basic directory structure for a Gauge project. ```bash gauge init js ``` -------------------------------- ### Generate Gauge Steps with Taiko Recorder Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Use Taiko's interactive recorder to generate Gauge steps. Run `npx taiko` in your project directory and use commands like `openBrowser()`, `goto()`, `write()`, and `press()`. ```bash npx taiko > openBrowser() > goto('google.com') > write('Gauge test automation') > press('Enter') ``` -------------------------------- ### Block Network Requests with Taiko Intercept Source: https://github.com/getgauge/taiko/blob/master/README.md Use the `intercept` API to block specific network requests on a page, such as analytics or other resources. No additional setup is required. ```javascript intercept("https://www.google-analytics.com/analytics.js"); ``` -------------------------------- ### Launching Taiko Recorder Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/overview.md Command to launch the Taiko recorder, which allows interactive script writing by recording user actions in the browser. ```bash $ npx taiko ``` -------------------------------- ### Resume Taiko Session with REPL Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/record_and_run_tests.md Use the `repl()` API in a script to launch the Taiko REPL after executing predefined commands. This allows for interactive continuation of a test flow. ```javascript const { openBrowser, goto, write, click } = require('taiko'); const { repl } = require('taiko/recorder'); (async () => { try { await openBrowser(); await goto("google.com"); await click("I agree"); // remove this line if you run headless, because the cookie consent will not appear await write("taiko test automation"); await click("Google Search"); // Launchs the REPL after executing // the commands above await repl(); } catch (error) { console.error(error); } finally { closeBrowser(); } })(); ``` -------------------------------- ### Build Taiko Docker Image Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/taiko_in_docker.md Build the Docker image for running Taiko tests. Ensure you are in the project's root directory. ```bash docker build -t gauge-taiko . ``` -------------------------------- ### Load Taiko Plugins in REPL Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/record_and_run_tests.md Use the `--plugin` option to load Taiko plugins, such as diagnostics, into the REPL environment for extended functionality. ```bash npx taiko --plugin taiko-diagnostics > openBrowser(); > diagnostics.startTracing(); > goto('google.com'); > diagnostics.endTracing(); ``` -------------------------------- ### Optimize Chrome Instances for Parallel Runs Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/frequently_asked_questions.md Use recommended Chromium command-line arguments to improve load times when running tests in parallel on cloud environments. ```javascript await openBrowser({args: [ '--disable-gpu', '--disable-dev-shm-usage', '--disable-setuid-sandbox', '--no-first-run', '--no-sandbox', '--no-zygote']}); ``` -------------------------------- ### Ignoring Taiko Implicit Assertions Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/assertions.md Use a try-catch block to ignore Taiko's implicit assertions. This allows you to handle errors gracefully, for example, when an element might not be present. ```javascript const { openBrowser, goto, click, closeBrowser } = require('taiko'); (async () => { await openBrowser(); await goto("google.com"); try { await click("Google Search"); } catch(e) { //Ignore or log the error. } finally { closeBrowser(); } })(); ``` -------------------------------- ### Emulation Settings Source: https://github.com/getgauge/taiko/wiki/Taiko-CDP-Dependencies APIs for emulating device metrics and geolocation. ```APIDOC ## Emulation.setDeviceMetricsOverride ### Description Overrides the device metrics. ### Method Emulation.setDeviceMetricsOverride ### Endpoint N/A (CDP API) ### Parameters None explicitly documented for Taiko API. ### Request Example N/A ### Response N/A ## Emulation.setGeolocationOverride ### Description Overrides the geolocation. ### Method Emulation.setGeolocationOverride ### Endpoint N/A (CDP API) ### Parameters None explicitly documented for Taiko API. ### Request Example N/A ### Response N/A ``` -------------------------------- ### Automate Browser Actions in Taiko REPL Source: https://github.com/getgauge/taiko/blob/master/README.md Performs actions like navigating, writing text, and clicking elements directly in the Taiko REPL. ```bash > goto("google.com/?hl=en") > write("taiko test automation") > click("Google Search") ``` -------------------------------- ### Create Test File for Mocha Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Create a directory named 'test' and a file named 'test.js' within it to write your Mocha tests. ```bash mkdir test $EDITOR test/test.js # or create this file using any editor ``` -------------------------------- ### Get all elements using CSS selector Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/working_with_element_lists.md Use `$('.selector').elements()` to retrieve an array of all `ElementWrapper` objects matching the CSS selector. This is a versatile way to access multiple elements on a page. ```javascript var fruits = await $('.fruit').elements(); ``` -------------------------------- ### Automate Browser Actions in REPL Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/record_and_run_tests.md Interact with the browser by typing Taiko API commands directly into the REPL. Actions are performed sequentially. ```bash > openBrowser() ``` ```bash > goto("google.com") ``` ```bash > click("I agree") ``` ```bash > write("taiko test automation") ``` ```bash > click("Google Search") ``` -------------------------------- ### Get all elements using XPath selector Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/working_with_element_lists.md Use `$("//xpath").elements()` to retrieve an array of all `ElementWrapper` objects matching the XPath selector. This provides flexibility for complex element selection. ```javascript var fruits = await $("//li[@class='fruit']").elements(); ``` -------------------------------- ### Proximity Selector Example: Nested Source: https://github.com/getgauge/taiko/wiki/Taiko's-Proximity-Selector Illustrates a nested proximity selector, finding 'taiko' near an element that is itself located above 'browser'. Nested selectors enable complex spatial relationships to be defined for element selection. ```javascript text('taiko', near(text('automation', above('browser')))) ``` -------------------------------- ### Handle Touch Events with JavaScript Source: https://github.com/getgauge/taiko/blob/master/tests/functional-tests/specs/data/touch.html Set up event listeners for touchstart, touchend, and touchmove on a button element. This code is intended for use within a browser environment where these events are supported. ```javascript window.result = []; const button = document.querySelector('button'); console.log(button); button.style.height = '200px'; button.style.width = '200px'; button.focus(); button.addEventListener('touchstart', event => { log('Touchstart:', ...Array.from(event.changedTouches).map(touch => touch.identifier)); }); button.addEventListener('touchend', event => { log('Touchend:', ...Array.from(event.changedTouches).map(touch => touch.identifier)); }); button.addEventListener('touchmove', event => { log('Touchmove:', ...Array.from(event.changedTouches).map(touch => touch.identifier)); }); function log(...args) { console.log.apply(console, args); result.push(args.join(' ')); } function getResult() { let temp = result; result = []; return temp; } ``` -------------------------------- ### Proximity Selector Algorithm: Nested Search Source: https://github.com/getgauge/taiko/wiki/Taiko's-Proximity-Selector This pseudocode explains the logic for nested proximity searches. It indicates that the search starts from the innermost proximity condition and recursively applies the combinatorial search until the final element is identified. ```pseudocode //Nested search of A on proximity to B which is on proximity to C Starting from the innermost: call combinatorial search recursively until the final element is found ``` -------------------------------- ### Plugin Initialization with Hooks Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/writing_plugins.md Plugins are initialized by calling the 'init' method, which receives Taiko and event handler instances. The 'registerHooks' callback allows plugins to register behavior alterations. ```javascript init(taiko, eventHandlerProxy, descEvent, registerHooks){ registerHooks({ preConnectionHook: (target, options) => { return {target,options} } }) } ``` -------------------------------- ### Get a specific list item by index Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/working_with_element_lists.md Use `listItem({ selector: 'value' }).element(index)` to fetch a specific `ElementWrapper` from a list of matches using its zero-based index. This allows direct access to individual elements. ```javascript var fruit = await listItem({class: "fruit"}).element(0); // Prints Apple console.log(fruit); ``` ```javascript var fruit = await listItem({class: "fruit"}).element(3); // Prints Pear console.log(fruit); ``` -------------------------------- ### Get nth element using index-based CSS selector Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/working_with_element_lists.md Use CSS selectors with `:nth-child(n)` to directly select the nth element. Note that these indexes are one-based. This method is useful for targeting specific elements in a sequence. ```javascript //Returns Orange var fruit = await $(".fruit:nth-child(2)").text(); ``` -------------------------------- ### Get text of the first matching list item Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/working_with_element_lists.md Use `listItem({ selector: 'value' }).text()` to retrieve the text content of the first element that matches the provided selector criteria. This method is useful for fetching data from lists. ```javascript // Returns Apple await listItem({class: "fruit"}).text(); ``` -------------------------------- ### Get nth element using index-based XPath selector Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/working_with_element_lists.md Use XPath selectors with `[n]` to directly select the nth element. Note that these indexes are one-based. This method is effective for precise element targeting within a document structure. ```javascript //Returns Melon var fruit = await $("//li[@class='fruit'][3]").text(); ``` -------------------------------- ### Launch Taiko Recorder with Custom Browser Path Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/record_and_run_tests.md Set the TAIKO_BROWSER_PATH environment variable to launch Taiko's recorder with a specific browser executable. This is useful for using browsers other than the one bundled with Taiko. ```bash TAIKO_BROWSER_PATH=/complete/path/to/browser/executable/file npx taiko ``` -------------------------------- ### Run Existing Taiko Script with npx Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/installing.md Execute existing Taiko scripts using `npx` with the script file name. ```bash npx taiko sample.js ``` -------------------------------- ### Run Jest Tests Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Execute your Jest test suite using the npx jest command. This will discover and run all tests defined in your project. ```bash npx jest ``` -------------------------------- ### Emulate Device Viewport with Taiko Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/record_and_run_tests.md Use the --emulate-device option to simulate specific devices, such as 'iPhone X', by configuring the browser's viewport. Refer to devices.js for a full list of supported devices. ```bash npx taiko --emulate-device 'iPhone X' ``` -------------------------------- ### Taiko Basic Actions with Implicit Assertions Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/assertions.md This snippet demonstrates basic Taiko actions like opening a browser, navigating, and clicking. Tests will fail if elements are not visible or actions cannot be performed due to implicit assertions. ```javascript const { openBrowser, goto, click, closeBrowser } = require('taiko'); (async () => { await openBrowser(); await goto("google.com"); await click("Google Search"); })(); ``` -------------------------------- ### Run Taiko Test Script Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/record_and_run_tests.md Execute a saved Taiko JavaScript test script from the command line. ```bash npx taiko googlesearch.js ``` -------------------------------- ### Run Test Script with Observe Mode Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/record_and_run_tests.md Run a Taiko test script with the `--observe` flag to see the browser actions and have delays between steps. ```bash npx taiko googlesearch.js --observe ``` -------------------------------- ### Run Taiko Script with Observe Mode Source: https://github.com/getgauge/taiko/blob/master/README.md Executes a Taiko script and opens a browser window to observe the actions. Useful for debugging. ```bash $ taiko googlesearch.js --observe ``` -------------------------------- ### Emulate Network Conditions with Taiko Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/record_and_run_tests.md Utilize the --emulate-network option to simulate various network conditions like 'Regular2G', 'WiFi', or 'Offline'. This helps in testing how your application performs under different network constraints. ```bash npx taiko --emulate-network 'Regular2G' ``` -------------------------------- ### Generate API JSON with documentation.js Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/README.md This command uses documentation.js to parse JSDoc comments from specified Taiko source files and generate an API JSON file. Ensure the TAIKO_SKIP_DOCUMENTATION environment variable is not set to true. ```bash npx documentation build --shallow lib/taiko.js lib/elementWrapper/*.js -o lib/api.json ``` -------------------------------- ### Run Mocha Tests Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Execute your Mocha test suite using the npx mocha command. This will run all tests found in your project. ```bash npx mocha ``` -------------------------------- ### Overlay Actions Source: https://github.com/getgauge/taiko/wiki/Taiko-CDP-Dependencies APIs for highlighting elements on the page. ```APIDOC ## Overlay.highlightQuad ### Description Highlights a quadrilateral region on the page. ### Method Overlay.highlightQuad ### Endpoint N/A (CDP API) ### Parameters None explicitly documented for Taiko API. ### Request Example N/A ### Response N/A ## Overlay.highlightRect ### Description Highlights a rectangular region on the page. ### Method Overlay.highlightRect ### Endpoint N/A (CDP API) ### Parameters None explicitly documented for Taiko API. ### Request Example N/A ### Response N/A ## Overlay.hideHighlight ### Description Hides any current highlights on the page. ### Method Overlay.hideHighlight ### Endpoint N/A (CDP API) ### Parameters None explicitly documented for Taiko API. ### Request Example N/A ### Response N/A ``` -------------------------------- ### Input Events Source: https://github.com/getgauge/taiko/wiki/Taiko-CDP-Dependencies APIs for dispatching input events like mouse and keyboard actions. ```APIDOC ## Input.dispatchMouseEvent ### Description Dispatches a mouse event. ### Method Input.dispatchMouseEvent ### Endpoint N/A (CDP API) ### Parameters None explicitly documented for Taiko API. ### Request Example N/A ### Response N/A ## Input.dispatchKeyEvent ### Description Dispatches a key event. ### Method Input.dispatchKeyEvent ### Endpoint N/A (CDP API) ### Parameters None explicitly documented for Taiko API. ### Request Example N/A ### Response N/A ## Input.dispatchTouchEvent ### Description Dispatches a touch event. ### Method Input.dispatchTouchEvent ### Endpoint N/A (CDP API) ### Parameters None explicitly documented for Taiko API. ### Request Example N/A ### Response N/A ``` -------------------------------- ### Run Taiko Script from Terminal Source: https://github.com/getgauge/taiko/blob/master/README.md Executes a Taiko JavaScript test script from the command line. ```bash $ taiko googlesearch.js ``` -------------------------------- ### Running Taiko Test with Observe Mode Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/overview.md Command to run a Taiko test script with the `--observe` flag, which allows you to see the browser executing the test actions visually. ```bash $ npx taiko test.js --observe ``` -------------------------------- ### Taiko CLI Command to Run a Test Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/overview.md Command to execute a Taiko test script using Node.js. This command will download and run tests in headless mode by default. ```bash $ npx taiko test.js ``` -------------------------------- ### Plugin Package.json Capability Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/writing_plugins.md To enable execution functionality for a plugin as a subcommand, add the 'subcommands' capability in its package.json file. ```json capability:['subcommands'] ``` -------------------------------- ### Running a Simple Taiko Test Script Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/overview.md A basic Taiko script to open a browser, navigate to a URL, write text, press Enter, and close the browser. This is a common pattern for end-to-end testing. ```javascript const { openBrowser, goto, write, click, closeBrowser } = require('taiko'); (async () => { await openBrowser(); await goto("google.com"); await write("taiko test automation"); await press("Enter"); await closeBrowser(); })(); ``` -------------------------------- ### Launch Taiko with Firefox Nightly Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/experimental_features.md Set the TAIKO_BROWSER_PATH environment variable to the Firefox Nightly executable path before running Taiko. Note known issues with Firefox support. ```bash TAIKO_BROWSER_PATH="/Applications/Firefoxnightly.app/Contents/MacOS/firefox" npx taiko ``` -------------------------------- ### Run Gauge Tests Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Execute your Gauge tests using the npm test script. This assumes you have configured a test script in your package.json. ```bash npm test ``` -------------------------------- ### Default Screenshot in REPL Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/taking_screenshots.md Take a default screenshot in the REPL. The image will be saved in the scripts directory with a randomized name. ```javascript > screenshot() ✔ Screenshot is created at Screenshot-1592405213958.png ``` -------------------------------- ### Displaying Alerts with JavaScript Source: https://github.com/getgauge/taiko/blob/master/tests/functional-tests/specs/data/HTMLElements.html Shows how to trigger a JavaScript alert box. This is useful for simple notifications or confirmations. ```javascript var show = function (message) { alert(message); } ``` -------------------------------- ### Generate JavaScript Test Script Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/record_and_run_tests.md Use the `.code` command in the REPL to generate a JavaScript file based on the recorded session. This code can be copied or saved to a file. ```bash > .code ``` ```javascript const { openBrowser, goto, write, click } = require('taiko'); (async () => { try { await openBrowser(); await goto("google.com"); await click("I agree") await write("taiko test automation"); await click("Google Search"); } catch (error) { console.error(error); } finally { closeBrowser(); } })(); ``` -------------------------------- ### Configure File Download Path Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/file_upload_and_download.md Configure Taiko to allow file downloads to a specified directory using `Page.setDownloadBehavior`. This is useful for testing download functionality. ```javascript const { goto, client, click } = require('taiko'), path = require('path'), fs = require('fs'), assert = require('assert') (async () => { var downloadPath = path.resolve(__dirname, 'data', 'downloaded'); try { await openBrowser(); await client().send('Page.setDownloadBehavior', { behavior: 'allow', downloadPath: downloadPath, }); await goto('http://example.org/download'); // ensure that file_upload.js is run before this, // to allow the file to be available for download await click('foo.txt'); sleep(1000); expect(path.join(downloadPath, 'foo.txt')).to.exist; assert.ok(fs.existsSync(path.join(downloadPath, 'foo.txt'))) } catch (e) { console.error(e); } finally { await closeBrowser(); if (fs.existsSync(path.join(downloadPath, 'foo.txt'))) { fs.unlinkSync(path.join(downloadPath, 'foo.txt')); } } })(); ``` -------------------------------- ### Run Taiko Script with taiko command Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/integrating_with_test_runners.md Execute Taiko scripts directly using the `taiko` command. This runner logs command execution details to the console. ```bash > taiko google.js ✔ Browser opened ✔ Navigated to URL http://google.com ✔ Wrote Taiko testing into the focused element. ✔ Pressed the Enter key ✔ Browser closed ``` -------------------------------- ### Plugin Capability in package.json Source: https://github.com/getgauge/taiko/wiki/Taiko-Plugin To enable subcommand execution for a plugin, add the 'capability' field with 'subcommands' to its package.json file. This allows Taiko to recognize and utilize the plugin's execution functionality. ```json capability:[‘subcommands’] ``` -------------------------------- ### Exit Taiko REPL Source: https://github.com/getgauge/taiko/blob/master/packages/taiko/docs/record_and_run_tests.md Use the `.exit` command to stop the Taiko REPL session. Note that recording history is lost upon exit. ```bash > .exit ``` -------------------------------- ### Target API Methods and Events Source: https://github.com/getgauge/taiko/wiki/Taiko-CDP-Dependencies Documentation for Target domain APIs used by Taiko for managing browser targets (e.g., opening new tabs). ```APIDOC ## Target.createTarget ### Description Creates a new target (e.g., a new browser tab). ### Method POST ### Endpoint /jsonrpc/Target.createTarget ### Parameters #### Request Body - **url** (string) - Optional - The initial URL to navigate the new target to. ### Request Example ```json { "method": "Target.createTarget", "params": { "url": "http://example.com" } } ``` ### Response #### Success Response (200) - **targetId** (string) - The ID of the newly created target. ### Response Example ```json { "result": { "targetId": "target-id-456" } } ``` ``` ```APIDOC ## Target.setDiscoverTargets ### Description Enables or disables target discovery. ### Method POST ### Endpoint /jsonrpc/Target.setDiscoverTargets ### Parameters #### Request Body - **discover** (boolean) - Required - Whether to discover targets. - **filter** (string) - Optional - A filter for discovering targets. ### Request Example ```json { "method": "Target.setDiscoverTargets", "params": { "discover": true } } ``` ### Response #### Success Response (200) An empty object indicating success. ### Response Example ```json { "result": {} } ``` ``` ```APIDOC ## Target.targetCreated ### Description Fired when a new target is created. ### Method POST ### Endpoint /jsonrpc/Target.targetCreated ### Event This is an event, not a method to be called directly. ### Response Example ```json { "method": "Target.targetCreated", "params": { "targetInfo": { "targetId": "target-id-456", "type": "page", "title": "Example Page", "url": "http://example.com" } } } ``` ``` ```APIDOC ## Target.getTargetInfo ### Description Returns information about a target. ### Method POST ### Endpoint /jsonrpc/Target.getTargetInfo ### Parameters #### Request Body - **targetId** (string) - Required - The ID of the target to get information about. ### Request Example ```json { "method": "Target.getTargetInfo", "params": { "targetId": "target-id-456" } } ``` ### Response #### Success Response (200) - **targetInfo** (object) - Information about the target. ### Response Example ```json { "result": { "targetInfo": { "targetId": "target-id-456", "type": "page", "title": "Example Page", "url": "http://example.com" } } } ``` ``` -------------------------------- ### Proximity Selector Algorithm: Simple Search Source: https://github.com/getgauge/taiko/wiki/Taiko's-Proximity-Selector This pseudocode describes the algorithm for a simple proximity search. It iterates through all potential anchor elements (A) and for each, finds the closest reference element (B) that satisfies the specified proximity condition. ```pseudocode //simple search of A on proximity to B //proximity condition near, within, above, below, leftOf, rightOf A := get all A matchingAWithProximityToB := [] for each a of A: B : = get all B for each b of B: if ( b satisfy proximity condition && positional distance between(a,b) < closestB’s distance ): closestB = b if(closestB): matchingAWithProximityToB.push({a,b}) return sort(matchingAWithProximityToB by distance) ```