### Install Dependencies Source: https://github.com/devexpress/testcafe/blob/master/examples/using-assertions/README.md Clone the repository, navigate to the examples directory, and install project dependencies using npm. ```sh git clone https://github.com/DevExpress/testcafe.git cd examples/using-assertions npm install ``` -------------------------------- ### Install TestCafe Dependencies Source: https://github.com/devexpress/testcafe/blob/master/examples/basic/README.md Clone the repository and install the necessary dependencies for the basic examples. ```sh git clone https://github.com/DevExpress/testcafe.git cd examples/basic npm install ``` -------------------------------- ### Install TestCafe Dependencies Source: https://github.com/devexpress/testcafe/blob/master/CONTRIBUTING.md After cloning the TestCafe repository, navigate to the root directory and run this command to install all necessary project dependencies. ```sh npm install ``` -------------------------------- ### Install Ruby Dependencies Source: https://github.com/devexpress/testcafe/wiki/How-to-publish-the-website-on-GitHub-Pages Run this command to install necessary Ruby gems for website building. Ensure Ruby version compatibility. ```sh bundle install ``` -------------------------------- ### Install TestCafe Globally from Package Source: https://github.com/devexpress/testcafe/blob/master/CONTRIBUTING.md After creating a package with `npm pack`, use this command to install it globally on your system. Remember to replace `path/to/package` with the actual path to the generated `.tgz` file. ```sh npm install -g path/to/package ``` -------------------------------- ### Install TestCafe Globally Source: https://github.com/devexpress/testcafe/blob/master/README.md Install TestCafe globally using npm. This command makes TestCafe available system-wide for immediate use. ```bash npm install -g testcafe ``` -------------------------------- ### Check Node.js and npm Versions Source: https://github.com/devexpress/testcafe/blob/master/CONTRIBUTING.md Run this command to verify that Node.js and npm are installed on your system. Ensure you are using an actively maintained version of Node.js. ```sh node -v; npm -v ``` -------------------------------- ### Clone TestCafe Repository Source: https://github.com/devexpress/testcafe/blob/master/examples/running-tests-in-firefox-and-chrome-using-travis-ci/README.md Use this command to clone the TestCafe repository to your local machine. This is the first step to access the example files. ```sh git clone https://github.com/DevExpress/testcafe.git ``` -------------------------------- ### Package TestCafe with npm pack Source: https://github.com/devexpress/testcafe/blob/master/CONTRIBUTING.md This command creates a compressed package file of the TestCafe framework, which can then be installed using npm. ```sh npm pack ``` -------------------------------- ### Run TestCafe Tests Source: https://github.com/devexpress/testcafe/blob/master/examples/basic/README.md Execute the installed TestCafe tests using the npm test command. ```sh npm test ``` -------------------------------- ### Global Hooks Example Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/global-hooks/pages/index.html This code sets up event listeners for various hooks (beforeEach, test, afterEach, testBefore, testAfter) and a button to throw an error based on the accumulated state. It's useful for debugging and understanding hook execution order. ```javascript let state = ''; document.querySelector('#beforeEach').addEventListener('click', function () { state += '[beforeEach]'; }); document.querySelector('#test').addEventListener('click', function () { state += '[test]'; }); document.querySelector('#afterEach').addEventListener('click', function () { state += '[afterEach]'; }); document.querySelector('#testBefore').addEventListener('click', function () { state += '[testBefore]'; }); document.querySelector('#testAfter').addEventListener('click', function () { state += '[testAfter]'; }); document.querySelector('#failAndReport').addEventListener('click', function () { throw new Error(state); }); ``` -------------------------------- ### Event Listener Setup for Hover Events Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/hover/pages/index.html Sets up event listeners for various mouse events on specified elements. This is useful for tracking user interactions like hovering. ```javascript window.eventLog = []; const container = document.getElementById('container'); const child1 = document.getElementById('child1'); const child2 = document.getElementById('child2'); const content1 = document.getElementById('content1'); const content2 = document.getElementById('content2'); function eventHandler (e) { let modifiers = ''; if (e.altKey) modifiers += ':alt'; if (e.ctrlKey) modifiers += ':ctrl'; if (e.metaKey) modifiers += ':meta'; if (e.shiftKey) modifiers += ':shift'; window.eventLog.push(e.type + ':' + e.target.id + ':' + e.currentTarget.id + modifiers); } function listenElementEvents (element) { element.addEventListener('mouseover', eventHandler); element.addEventListener('mouseenter', eventHandler); element.addEventListener('mouseout', eventHandler); element.addEventListener('mouseleave', eventHandler); } listenElementEvents(container); listenElementEvents(content1); listenElementEvents(content2); listenElementEvents(child1); listenElementEvents(child2); ``` -------------------------------- ### Handle Click and Double Click Events Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/double-click/pages/index.html This example shows how to set up event listeners for both single and double clicks on a button. It tracks the number of single clicks before a double click occurs, throwing an error to indicate the click count. ```javascript let clickCount = 0; document.getElementById('button').addEventListener('click', function () { clickCount++; }); document.getElementById('button').addEventListener('dblclick', function () { throw new Error('Click on button raised ' + clickCount + ' times. Double click on button raised.'); }); ``` -------------------------------- ### Basic TestCafe Test Structure Source: https://github.com/devexpress/testcafe/blob/master/README.md A simple TestCafe test demonstrating fixture setup, page navigation, typing text, clicking a button, and asserting element text. ```javascript import { Selector } from 'testcafe'; // first import testcafe selectors fixture `Getting Started`// declare the fixture .page `https://devexpress.github.io/testcafe/example`; // specify the start page //then create a test and place your code within it test('My first test', async t => { await t .typeText('#developer-name', 'John Smith') .click('#submit-button') // Use the assertion to check if actual header text equals expected text .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!'); }); ``` -------------------------------- ### Send POST Request with Authorization Header Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/request-pipeline/xhr/pages/index.html This example demonstrates sending a POST request with an 'authorization' header. It retrieves and displays the 'authorization' response header upon a successful 200 status. ```javascript document.querySelector('#auth-header').addEventListener('click', () => { const xhr = new XMLHttpRequest(); xhr.open('POST', '/xhr/auth-header'); xhr.setRequestHeader('authorization', 'authorization-string'); xhr.send(); xhr.onload = function() { if (xhr.status = 200) { const xhrResultDiv = document.createElement('div'); xhrResultDiv.id = 'xhr-result'; xhrResultDiv.textContent = xhr.getResponseHeader('authorization'); document.body.appendChild(xhrResultDiv); } }; }) ``` -------------------------------- ### Create and Append Iframe Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/hammerhead/gh-2622/pages/index.html This snippet demonstrates how to create an iframe element, set its source, and append it to the document's body. This is a common setup for testing iframe interactions. ```javascript var iframe = document.createElement('iframe'); iframe.src = 'iframe.html'; document.body.appendChild(iframe); ``` -------------------------------- ### JavaScript for Simulating Element Movement Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/gh-1521/pages/moving-element.html Initializes global counters for clicks and movement, sets up an event listener for clicks on the target element, and defines a function to start the element's movement. The movement is simulated using `setInterval` to update the element's `top` style property. ```javascript const target = document.getElementById('target'); window.clickCount = 0; window.moveCount = 0; target.addEventListener('click', function () { window.clickCount++; }); let movingInterval = null; function startMoving () { // NOTE: simulate element transition movingInterval = window.setInterval(function () { window.moveCount++; target.style.top = window.moveCount * 10 + 'px'; if (window.moveCount > 50) window.clearInterval(movingInterval); }, 10); } document.getElementById('start').addEventListener('mouseleave', function () { startMoving(); }); ``` -------------------------------- ### JavaScript Function Example Source: https://github.com/devexpress/testcafe/blob/master/test/client/fixtures/automation/content-editable/regression-test/index.html A simple JavaScript function that returns a string. This might be used for testing script execution within a content-editable context. ```javascript function testScriptTagFunction() { return 'abc'; } ``` -------------------------------- ### CSS for Moving Element Test Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/gh-1521/pages/moving-element.html Defines the styles for the target and start elements, including their initial positions and appearance. The target element is styled to be yellow and positioned absolutely, while the start element is red. ```css #target, #start { width: 10px; height: 10px; position: absolute; } #target { background-color: yellow; top: 0; left: 150px; } #start { background-color: red; top: 0; left: 0px; } ``` -------------------------------- ### Show Alert on Click Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/roles/pages/index.html This snippet attaches an event listener to a button that triggers a simple JavaScript alert. It's a basic example of handling user interactions. ```javascript document.querySelector('#show-alert').addEventListener('click', function () { alert('Hey!'); }); ``` -------------------------------- ### Define a Getter with a Delayed Side Effect Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/assertions/pages/index.html This example demonstrates defining a getter property on the window object that has a delayed side effect. When the getter is accessed, it schedules an update to a local variable using `window.setTimeout`. ```javascript let value = 4; Object.defineProperty(window, 'someVar', { get: function () { window.setTimeout(function () { value = 2; }, 400); return value; } }) ``` -------------------------------- ### Build Website for Production Source: https://github.com/devexpress/testcafe/wiki/How-to-publish-the-website-on-GitHub-Pages Execute this command to build the website for production deployment. This is typically done after checking out the master branch. ```sh gulp build-website-production ``` -------------------------------- ### Send GET Request with 204 Status Code using XMLHttpRequest Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/request-hooks/pages/request-logger/without-response-body.html This snippet demonstrates sending a GET request that is expected to return a 204 No Content status, logging the outcome. ```javascript function sendXhrRequest (method, url, statusElement) { const xhr = new XMLHttpRequest(); xhr.addEventListener('load', function () { statusElement.textContent = 'Request completed'; }); xhr.addEventListener('error', function () { statusElement.textContent = 'Request failed'; }); xhr.open(method, url); xhr.send(); } const send204RequestBtn = document.getElementById('send-204-request'); const status204RequestDiv = document.getElementById('204-status-request'); send204RequestBtn.addEventListener('click', function () { sendXhrRequest('GET', 'http://localhost:3000/204', status204RequestDiv); }); ``` -------------------------------- ### Get Browser Info with XMLHttpRequest Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/request-hooks/pages/request-logger/multi-browser.html This snippet shows how to use XMLHttpRequest to make a GET request to '/get-browser-name' and update button text upon successful load or throw an error on failure. It's useful for client-side interactions that require fetching data. ```javascript const button = document.getElementsByTagName('button')[0]; button.addEventListener('click', function () { const xhr = new XMLHttpRequest(); xhr.open('GET', '/get-browser-name'); xhr.addEventListener('load', function (e) { button.textContent = 'Done'; }); xhr.addEventListener('error', function (e) { throw new Error('XMLHttpRequest for `/get-browser-name` route was finished with error.'); }); xhr.send(); }); ``` -------------------------------- ### Build TestCafe Project Source: https://github.com/devexpress/testcafe/blob/master/CONTRIBUTING.md Execute this command in the root directory of the TestCafe repository to build the project from source. ```sh npx gulp build ``` -------------------------------- ### Handle Button Click Event Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/gh-3924/pages/index.html Sets up a click event listener for a button. When clicked, it updates a global `window.clicked` flag to true and positions the button dynamically. ```javascript window.clicked = false; function onClick () { window.clicked = true; } var button = document.querySelector('button'); button.addEventListener('click', onClick); button.style.marginTop = document.documentElement.clientHeight - button.clientHeight - 20 + 'px'; ``` -------------------------------- ### Set Value in Local Storage and Open Link in New Window Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/run-options/disable-page-caching/pages/index.html This snippet shows how to set an item in local storage and then open a link in a new browser window using JavaScript. It's useful for simulating user interactions that involve data persistence and navigation. ```javascript var firstBtn = document.getElementById("first"); var secondBtn = document.getElementById("second"); firstBtn.addEventListener('click', function () { window.localStorage.setItem( 'testItem', JSON.stringify({ link: './third.html' }) ); }); secondBtn.addEventListener('click', function () { window.open('./second.html', '_blank'); }); ``` -------------------------------- ### Accessing File Input Value Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/gh-7886/pages/index.html This snippet shows how to get the value of a file input element. Ensure the element with ID 'upload' exists in the DOM. ```javascript const uploadInput = document.getElementById('upload'); console.log(uploadInput.value); ``` -------------------------------- ### Initialize and Communicate with a Web Worker Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/hammerhead/worker/pages/index.html Sets up a Web Worker to process input from two elements and display the result. Use this for offloading heavy computations from the main thread. ```javascript const first = document.getElementById('first'); const second = document.getElementById('second'); const result = document.getElementById('result'); const worker = new Worker('worker.js'); function sendDataToWorker () { worker.postMessage({ first: first.value, second: second.value }); } first.oninput = sendDataToWorker; second.oninput = sendDataToWorker; worker.onmessage = function (e) { result.value = e.data; } ``` -------------------------------- ### Copy Deployed Site Files Source: https://github.com/devexpress/testcafe/wiki/How-to-publish-the-website-on-GitHub-Pages Use this command to copy the built website files from the deploy directory to the root of the repository. This command is for bash environments. ```sh cp -fR site/deploy/**/* . ``` -------------------------------- ### Select Text in Textarea Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/raw/select-text/pages/index.html This snippet verifies text selection within a textarea element by checking the selection start and end offsets. It handles both touch and mouse events. ```javascript const touchDevice = isTouchDevice(); document.getElementById('textarea').addEventListener(touchDevice ? 'touchend' : 'mouseup', function () { if (this.selectionStart === 1 && this.selectionEnd === 5) throw new Error('Selected text in textarea'); }); ``` -------------------------------- ### Listen to 'beforeunload' event with context check Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/gh-6563/pages/index.html This snippet demonstrates how to correctly listen to the 'beforeunload' event on the window object. It includes a custom adapter for event listening and a callback function that explicitly checks for the 'this' context to prevent errors. ```javascript (function () { 'use strict'; var domAdapter = { listen (element, event, callback) { element.addEventListener(event, callback); } } const callback = (function(){ return function () { if (!this) throw new Error('this is undefined'); } })(); domAdapter.listen(window, 'beforeunload', callback); })() ``` -------------------------------- ### Initialize Hammerhead and TestCafe Runner Source: https://github.com/devexpress/testcafe/blob/master/test/client/data/runner/iframe.html Sets up Hammerhead for processing and initializes the TestCafe legacy runner. This code is essential for the iframe environment to function correctly. ```javascript function getTestCafeModule (module) { return window['%' + module + '%']; } //Hammerhead setup const hammerhead = getTestCafeModule('hammerhead'); const INSTRUCTION = hammerhead.PROCESSING_INSTRUCTIONS.dom.script; hammerhead.utils.destLocation.forceLocation('http://localhost/sessionId/https://example.com'); hammerhead.start({ sessionId: 'sessionId' }); const testCafeLegacyRunner = getTestCafeModule('testCafeLegacyRunner'); const sandboxedJQuery = testCafeLegacyRunner.get('./sandboxed-jquery'); const iframeDispatcher = testCafeLegacyRunner.get('./iframe-dispatcher'); sandboxedJQuery.init(window); ``` -------------------------------- ### Link TestCafe Locally with npm link Source: https://github.com/devexpress/testcafe/blob/master/CONTRIBUTING.md Use this command in the root of the testcafe directory to create a symbolic link for local development. Then, link it in your test project directory. ```sh npm link ``` ```sh npm link testcafe ``` -------------------------------- ### JavaScript Busy-Wait Loop Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/multiple-windows/pages/api/child-3.html This snippet implements a busy-wait loop that pauses execution for a specified duration. It's a basic example of how to create a delay without using asynchronous functions. ```javascript const DATE_NOW = Date.now(); const LOCK_TIMEOUT = 10000; while (Date.now() < DATE_NOW + LOCK_TIMEOUT) { } ``` -------------------------------- ### Send Request Status with Async Predicate Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/request-hooks/pages/api/request-filter-rule-async-predicate.html This function sends a request and updates the DOM with the response text. It's an example of how an asynchronous operation can be used within a request hook. ```javascript function sendRequest() { fetch('http://dummy-url.com/get') .then(res => { return res.text(); }) .then(text => { document.querySelector('h2').textContent = text; }); } ``` -------------------------------- ### Set Text Area Value and Log Input Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/gh-1388/pages/index.html Sets the value of a text area and logs the selection start position on each input event. This is useful for debugging text input behavior. ```javascript const textArea = document.getElementById('textarea'); textArea.value = 'First line\nSecond line'; window.selectionLog = []; textArea.addEventListener('input', function () { window.selectionLog.push(textArea.selectionStart); }); ``` -------------------------------- ### Create and Communicate with a Worker Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/gh-7675/pages/xhr.html Instantiates a Web Worker and sets up an event listener to handle messages from it. Ensure the worker script path is correct. ```javascript const worker = new Worker('http://localhost:3000/fixtures/regression/gh-7675/pages/worker2.js'); worker.addEventListener('message', handleWorkerMessage); ``` -------------------------------- ### Send Request and Filter Custom Headers Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/request-hooks/pages/api/change-remove-response-headers.html This snippet sends a POST request and filters custom headers starting with 'x-header-'. It then updates the UI to show the request status and the filtered headers. ```javascript const sendRequestBtn = document.getElementById('sendRequest'); const receivedHeaders = document.getElementById('result'); const requestStatusDiv = document.getElementById('requestStatus'); function filterCustomHeaders (headers) { const resultHeaders = {}; for (const [key, value] of headers.entries()) { if(key.startsWith('x-header-')) resultHeaders[key] = value; } return resultHeaders; } sendRequestBtn.addEventListener('click', () => { let customHeaders = {}; fetch('/echo-custom-request-headers-in-response-headers', { method: 'POST', headers: { 'x-header-1': 'different', 'x-header-4': 'value-4', 'x-header-5': 'value-5' } }) .then(res => { customHeaders = filterCustomHeaders(res.headers); return res.text(); }) .then(() => { requestStatusDiv.textContent = 'Received'; receivedHeaders.textContent = JSON.stringify(customHeaders, null, 4); }) .catch(err => { requestStatusDiv.textContent = 'Error'; receivedHeaders.textContent = err.toString(); }); }); ``` -------------------------------- ### Get Text Property of Title Element Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/hammerhead/gh-2350/pages/text-property-getters-of-title-element.html Retrieves and logs the 'text', 'innerHTML', and 'innerText' properties of the document's title element. Useful for verifying how different text content accessors behave. ```javascript var log = []; var titleElement = document.getElementsByTagName('title')[0]; log.push('text: ' + titleElement.text); log.push('innerHTML: ' + titleElement.innerHTML); log.push('innerText: ' + titleElement.innerText); ``` -------------------------------- ### Test Dragging to a Specific Offset Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/drag/pages/index.html Tests the drag functionality by verifying if an element is moved to a specific offset from its starting position. It checks for the correct position change and ensures the drag event was registered. ```javascript (function () { const touchDevice = isTouchDevice(); const draggable1 = document.getElementById('draggable-div-1'); const startPos = { x: 0, y: 0 }; const endPos = { x: 0, y: 0 }; let moveEventRaised = false; draggable1.addEventListener(touchDevice ? 'touchstart' : 'mousedown', function () { startPos.x = draggable1.offsetLeft; startPos.y = draggable1.offsetTop; }); draggable1.addEventListener(touchDevice ? 'touchmove' : 'mousemove', function () { moveEventRaised = true; }); draggable1.addEventListener(touchDevice ? 'touchend' : 'mouseup', function () { endPos.x = draggable1.offsetLeft; endPos.y = draggable1.offsetTop; if (moveEventRaised && endPos.x - startPos.x === 10 && endPos.y - startPos.y === 20) throw new Error('Drag to offset completed successfully'); else { throw new Error([ 'Drag was not completed successfully:', 'moveEventRaised: expected true but was ' + moveEventRaised + ';', 'left position offset: expected 10 but was ' + (endPos.x - startPos.x) + ';', 'top position offset: expected 10 but was ' + (endPos.y - startPos.y) + ';' ].join(' ')); } }); })(); ``` -------------------------------- ### Handle Link Click and Redirect Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/driver/pages/page1.html Attaches a click event listener to a link. After a delay, it redirects the window to 'index.html' with a query parameter. ```javascript document.getElementById('link').addEventListener('click', function () { window.setTimeout(function () { window.location = 'index.html?delay=2000'; }, 900); }); ``` -------------------------------- ### Initialize Page Load Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/hammerhead/gh-2418/pages/index.html Initiates the page loading process by scheduling the load function to run after a short delay. ```javascript function init() { setTimeout(load, 50); } ``` -------------------------------- ### Send HTTP Request with Fetch API Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/request-hooks/pages/request-mock/async-response-function.html This snippet uses the Fetch API to send a GET request and display the response text or an error message. It requires DOM elements with IDs 'sendRequest' and 'result'. ```javascript var sendRequestBtn = document.getElementById('sendRequest'); var resultSpan = document.getElementById('result'); sendRequestBtn.addEventListener('click', function () { fetch('http://one-dummy-url.com/get') .then(res => res.text()) .then(text => { resultSpan.textContent = text; }) .catch(err => { resultSpan.textContent = err.toString(); }); }); ``` -------------------------------- ### Handle Prompt Dialog in JavaScript Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/native-dialogs-handling/pages/prompt.html Use window.prompt() to display a prompt dialog to the user and capture their input. The result is then displayed on the page. ```javascript const res = window.prompt('Prompt:'); document.getElementById('result').textContent = res === null ? 'null' : res; ``` -------------------------------- ### Select Text in Input Field Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/raw/select-text/pages/index.html This code checks if the selection start and end offsets within an input element match expected values. It's useful for verifying text selection in input fields. ```javascript const touchDevice = isTouchDevice(); document.getElementById('input').addEventListener(touchDevice ? 'touchend' : 'mouseup', function () { if (this.selectionStart === 2 && this.selectionEnd === 4) throw new Error('Selected text in input'); }); ``` -------------------------------- ### Navigate to a New Page Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/selector/pages/index.html Attaches an event listener to trigger a page navigation to a new URL after a 1000ms delay. ```javascript document.querySelector('#newPage').addEventListener('click', function () { window.setTimeout(function () { document.location = 'http://localhost:3000/fixtures/api/es-next/selector/pages/new-page-element.html'; }, 1000); }); ``` -------------------------------- ### Instantiate a Worker Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/gh-7675/pages/import.html Create a new Worker instance by providing the path to the worker script. This is useful for offloading tasks to a separate thread. ```javascript const worker = new Worker('http://localhost:3000/fixtures/regression/gh-7675/pages/worker1.js'); ``` -------------------------------- ### Handle Error Throwing Event with TestCafe Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/raw/code-steps/pages/index.html This code demonstrates how to attach an event listener that throws an error when triggered. It's useful for testing error handling mechanisms within your application or TestCafe setup. ```javascript div.addEventListener('click', function () { throw new Error('error ocurred'); }); ``` -------------------------------- ### Run TestCafe Tests Source: https://github.com/devexpress/testcafe/blob/master/CONTRIBUTING.md Execute these shell commands to test your changes locally before submitting a pull request. Ensure all tests pass to meet contribution standards. ```shell gulp test-server gulp test-functional-local gulp test-client-local ``` -------------------------------- ### Enable Before Unload Dialog Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/native-dialogs-handling/pages/index.html Sets up the 'beforeunload' event handler to prompt the user before navigating away from the page. ```javascript document.getElementById('enableBeforeUnload').addEventListener('click', function () { window.onbeforeunload = function (e) { return 'Before unload'; }; }); ``` -------------------------------- ### Event Logging and Handling in JavaScript Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/gh-3501/pages/index.html This script sets up event listeners for focus and click events on various HTML elements. It logs the event type and target to the console and an on-page logger. Ensure the HTML has elements with IDs 'logger', 'label1', 'label2', 'radio', and 'checkbox'. ```javascript var eventLog = []; function consoleLog (text) { var logger = document.querySelector('#logger'); logger.innerHTML += text + '
'; } var label1 = document.querySelector('#label1'); var label2 = document.querySelector('#label2'); var radio = document.querySelector('#radio'); var checkbox = document.querySelector('#checkbox'); function handleEvent (event) { const text = event.type + '. Target: ' + event.target.id; eventLog.push(text); consoleLog(text); } label1.addEventListener('focus', handleEvent); label2.addEventListener('focus', handleEvent); label1.addEventListener('click', handleEvent); label2.addEventListener('click', handleEvent); radio.addEventListener('focus', handleEvent); checkbox.addEventListener('focus', handleEvent); ``` -------------------------------- ### Implement Drag and Drop Functionality Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/drag/pages/drag-and-drop.html This JavaScript code sets up event listeners for drag and drop operations. It handles `dragstart`, `dragover`, and `drop` events to move elements between containers and display dropped data. ```javascript const from = document.querySelector('#from'); const to = document.querySelector('#to'); const toDisplayValues = document.querySelector('#to-display-values'); const draggable = document.querySelector('#draggable'); from.addEventListener('dragstart', function (e) { e.dataTransfer.setData('text', e.target.children[0].id); }); to.addEventListener('dragover', function (e) { e.preventDefault(); }); toDisplayValues.addEventListener('dragover', function (e) { e.dataTransfer.setData('custom/type', 'customValue'); if (e.dataTransfer.getData('custom/type')) throw new Error("It should not be allowed to change dataTransfer data after dragstart event"); e.preventDefault(); }); to.addEventListener('drop', function (e) { e.preventDefault(); e.target.appendChild(document.getElementById(e.dataTransfer.getData('text'))); }); toDisplayValues.addEventListener('drop', function (e) { e.preventDefault(); const values = []; for (let i = 0; i < e.dataTransfer.types.length; i++) { values.push(e.dataTransfer.getData(e.dataTransfer.types[i])); } e.target.textContent = values.join(' - '); }); ``` -------------------------------- ### Create Editor with Placeholder (JavaScript) Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/gh-2205/pages/index.html This function appends a paragraph and a line break to an editor element and attaches a placeholder to it. Use this to dynamically set up editor instances. ```javascript function createEditor (editor, placeholder) { const paragraph = document.createElement('p'); const lineBreak = document.createElement('br'); editor.appendChild(paragraph); paragraph.appendChild(placeholder); paragraph.appendChild(lineBreak); } createEditor(document.getElementById('editor1'), document.getElementById('placeholder1')); createEditor(document.getElementById('editor2'), document.getElementById('placeholder2')); ``` -------------------------------- ### Configure Hammerhead Proxy and Force Location Source: https://github.com/devexpress/testcafe/blob/master/test/client/data/focus-blur-change/iframe.html Initializes the Hammerhead proxy with a specific cross-domain port and forces the browser's location to a proxied URL. Use this for setting up the testing environment. ```javascript const hammerhead = window['%hammerhead%']; hammerhead.utils.destLocation.forceLocation('http://localhost/sessionId/http://target_url'); hammerhead.start({ crossDomainProxyPort: 2000 }); ``` -------------------------------- ### Handle Button Click and Fetch Data Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/gh-7640/pages/index.html This snippet listens for a button click, fetches data from a local API, and updates the DOM with the JSON response. Ensure the API is running at http://127.0.0.1:3000/api/data. ```javascript const btn = document.querySelector('button'); btn.addEventListener('click', function() { fetch('http://127.0.0.1:3000/api/data') .then(res => res.json()) .then(res => { document.querySelector('div').innerHTML = JSON.stringify(res.data); }) }); ``` -------------------------------- ### Dynamically Create and Click Button Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/raw/click/pages/index.html Creates a new button element, appends it to the document after a delay, and makes it visible after another delay. A click listener on this button throws an error. ```javascript const newButton = document.createElement('input'); newButton.type = 'button'; newButton.id = 'new-button'; newButton.value = 'new-button'; newButton.style.display = 'none'; newButton.addEventListener('click', function () { throw new Error('Click on the new button raised'); }); window.setTimeout(function () { document.documentElement.appendChild(newButton); }, 1000); window.setTimeout(function () { newButton.style.display = ''; }, 2000); ``` -------------------------------- ### Click Handler with Multiple Fetch Requests Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/regression/gh-7977/pages/index.html This JavaScript code attaches an event listener to a button. When clicked, it executes a handler function that makes 100 fetch requests to a local server endpoint. ```javascript function handler () { for (let i = 0; i < 100; i++) { fetch('http://localhost:3000/api/data'); } } document.querySelector('button').addEventListener('click', handler); ``` -------------------------------- ### Handle Print Dialog Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/api/es-next/native-dialogs-handling/pages/index.html Initiates the browser's print dialog. Useful for testing print functionality. ```javascript document.getElementById('buttonPrint').addEventListener('click', function () { window.print(); }); ``` -------------------------------- ### Dynamically Generate HTML Page Source: https://github.com/devexpress/testcafe/blob/master/test/functional/fixtures/hammerhead/gh-2418/pages/index.html Generates the HTML content for a page and writes it to the document. This is used for setting up specific test environments. ```javascript function load() { var html = '\n' + '\n' + '\n' + 'Title\n' + '\n' + '