{"id":14156657,"url":"https://github.com/hdorgeval/testcafe-snippets","last_synced_at":"2025-04-19T18:09:22.428Z","repository":{"id":87275214,"uuid":"112738799","full_name":"hdorgeval/testcafe-snippets","owner":"hdorgeval","description":"Code snippets for TestCafe","archived":false,"fork":false,"pushed_at":"2019-02-22T21:29:08.000Z","size":290,"stargazers_count":57,"open_issues_count":0,"forks_count":6,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-18T08:37:17.273Z","etag":null,"topics":["e2e-testing","e2e-tests","snippets","testcafe","visual-studio-code","vscode","vscode-extension","vscode-snippets"],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hdorgeval.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2017-12-01T12:43:18.000Z","updated_at":"2024-03-28T13:02:26.000Z","dependencies_parsed_at":null,"dependency_job_id":"82e0a564-6abf-4669-8db4-4099c1359c49","html_url":"https://github.com/hdorgeval/testcafe-snippets","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hdorgeval%2Ftestcafe-snippets","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hdorgeval%2Ftestcafe-snippets/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hdorgeval%2Ftestcafe-snippets/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hdorgeval%2Ftestcafe-snippets/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hdorgeval","download_url":"https://codeload.github.com/hdorgeval/testcafe-snippets/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249758784,"owners_count":21321595,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["e2e-testing","e2e-tests","snippets","testcafe","visual-studio-code","vscode","vscode-extension","vscode-snippets"],"created_at":"2024-08-17T08:07:42.000Z","updated_at":"2025-04-19T18:09:22.406Z","avatar_url":"https://github.com/hdorgeval.png","language":null,"readme":"# Code snippets for TestCafe ([say goodbye to flakyness](say-goodbye-to-flakyness.md))\n\n[This Visual Studio Code Extension](https://marketplace.visualstudio.com/items?itemName=hdorgeval.testcafe-snippets) provides code snippets for TestCafe.\n\nUse the `tc-` prefix to access snippets:\n\n- [tc-angularjs-enable-debug](#tc-angularjs-enable-debug)\n- [tc-angularjs-get-object-from-scope](#tc-angularjs-get-object-from-scope)\n- [tc-assert-count](#tc-assert-count)\n- [tc-assert-exists](#tc-assert-exists)\n- [tc-client-function-ajax-request-with-jquery](#tc-client-function-ajax-request-with-jquery)\n- [tc-client-function-get-browser-user-agent](#tc-client-function-get-browser-user-agent)\n- [tc-client-function-get-something-from-dom](#tc-client-function-get-something-from-dom)\n- [tc-client-function-get-style-attribute](#tc-client-function-get-style-attribute)\n- [tc-client-function-set-style-attribute](#tc-client-function-set-style-attribute)\n- [tc-client-function-get-window-state](#tc-client-function-get-window-state)\n- [tc-client-function-measure-execution-time](#tc-client-function-measure-execution-time)\n- [tc-client-function-read-localstorage](#tc-client-function-read-localstorage)\n- [tc-client-function-scroll-to-element](#tc-client-function-scroll-to-element)\n- [tc-client-function-set-something-in-dom](#tc-client-function-set-something-in-dom)\n- [tc-client-function-write-to-localstorage](#tc-client-function-write-to-localstorage)\n- [tc-copy-paste-text](#tc-copy-paste-text)\n- [tc-ensure-field-is-ready-before-clicking-on-it](#tc-ensure-field-is-ready-before-clicking-on-it)\n- [tc-filter-hidden-elements](#tc-filter-hidden-elements)\n- [tc-filter-visible-elements](#tc-filter-visible-elements)\n- [tc-fixture-with-start-page](#tc-fixture-with-start-page)\n- [tc-fixture-with-start-page-and-hooks](#tc-fixture-with-start-page-and-hooks)\n- [tc-get-selected-option](#tc-get-selected-option)\n- [tc-import](#tc-import)\n- [tc-iterate-over-selected-checkboxes](#tc-iterate-over-selected-checkboxes)\n- [tc-maximize-window](#tc-maximize-window)\n- [tc-navigate-to-url](#tc-navigate-to-url)\n- [tc-pause-test-for-client-side-debugging](#tc-pause-test-for-client-side-debugging)\n- [tc-reload-browser](#tc-reload-browser)\n- [tc-remove-text](#tc-remove-text)\n- [tc-selector-with-options](#tc-selector-with-options)\n- [tc-select-an-option-by-content](#tc-select-an-option-by-content)\n- [tc-select-an-option-by-content-with-regex](#tc-select-an-option-by-content-with-regex)\n- [tc-select-an-option-by-exact-content](#tc-select-an-option-by-exact-content)\n- [tc-select-a-radio-button-by-value](#tc-select-a-radio-button-by-value)\n- [tc-select-first-non-empty-option](#tc-select-first-non-empty-option)\n- [tc-select-first-option](#tc-select-first-option)\n- [tc-select-last-option](#tc-select-last-option)\n- [tc-set-window-size-to-custom-width-and-height](#tc-set-window-size-to-custom-width-and-height)\n- [tc-set-window-size-to-fit-device](#tc-set-window-size-to-fit-device)\n- [tc-take-screenshot-of-an-element-in-dom](#tc-take-screenshot-of-an-element-in-dom)\n- [tc-test](#tc-test)\n- [tc-test-with-hooks](#tc-test-with-hooks)\n- [tc-type-text](#tc-type-text)\n- [tc-type-text-letter-by-letter](#tc-type-text-letter-by-letter)\n- [tc-wait-for-a-selector-to-appear](#tc-wait-for-a-selector-to-appear)\n- [tc-wait-for-a-selector-to-disappear](#tc-wait-for-a-selector-to-disappear)\n- [tc-wait-until-exists-property-of-selector-is-stable](#tc-wait-until-exists-property-of-selector-is-stable)\n\n## Supported languages (file extensions)\n\n* JavaScript (.js)\n* TypeScript (.ts)\n\n## Details\n\n### tc-angularjs-enable-debug\n\n```typescript\n// enable Angular debug info\nconst reloadWithDebugInfo = ClientFunction(() =\u003e {\n    const angular = (window as any).angular;\n    if (angular) {\n        angular.reloadWithDebugInfo();\n    }\n});\nawait reloadWithDebugInfo();\n```\n\n### tc-angularjs-get-object-from-scope\n\n```typescript\n// get object from angularjs scope\nconst getCustomObject = ClientFunction( () =\u003e {\n    const $ = (window as any).jQuery;\n    const scope = $(\"selector\").scope();\n    // inspect, in dev tools, the scope object todiscover available objects\n    // tslint:disable-next-line:no-console\n    console.log(\"scope: \", scope);\n    return scope.xxx;\n});\nconst myObject = await getCustomObject();\n```\n\n### tc-assert-count\n\n```typescript\n// assert for a count value\n// see http://devexpress.github.io/testcafe/example/\nconst selector = Selector(\"select#preferred-interface option\")\n    .with({visibilityCheck: true});\nawait t\n    .expect(selector.count).eql(3, {timeout: 5000});\n```\n\n### tc-assert-exists\n\n```typescript\n// assert the existence of a selector\n// see http://devexpress.github.io/testcafe/example/\nconst preferredInterfaceElement = \"select#preferred-interface\";\nconst selector = Selector(preferredInterfaceElement)\n    .find(\"option\")\n    .withExactText(\"JavaScript API\");\nawait t\n    .expect(selector.exists)\n        .ok(\n            `The element '${preferredInterfaceElement}' has no option named 'JavaScript API'`,\n            {timeout: 5000},\n        );\n```\n\n### tc-client-function-ajax-request-with-jquery\n\n```typescript\n// Client-side ajax request\n// client-side function used for sending the ajax request\nconst send = ClientFunction( (req: any) =\u003e {\n    return new Promise( (resolve) =\u003e {\n        const json: string = JSON.stringify(req);\n        const $ = (window as any).jQuery;\n        $.ajax({\n            contentType: \"application/json; charset=utf-8\",\n            data: json,\n            dataType: \"json\",\n            type: \"POST\",\n            url: \"https://reqres.in/api/users\",\n        })\n        .always( (httpResponse: XMLHttpRequest) =\u003e {\n            if (httpResponse \u0026\u0026 httpResponse.getAllResponseHeaders ===undefined) {\n                resolve(httpResponse);\n                return;\n            }\n            resolve({\n                responseHeaders: httpResponse.getAllResponseHeaders(),\n                responseText: httpResponse.responseText,\n                status: httpResponse.status,\n                statusText: httpResponse.statusText,\n            });\n        });\n    });\n});\n// request object that will be posted to the backend server\nconst request = {\n    firstName: \"john\",\n    lastName: \"Doe\",\n    requestTime: Date(),\n};\n// send request and get response\nconst response: XMLHttpRequest | any = await send(request);\n```\n\n### tc-client-function-get-browser-user-agent\n\n```typescript\n// you need to import {ClientFunction} from \"testcafe\";\nconst getBrowserUserAgent = ClientFunction(() =\u003e navigator.userAgent.toString());\nconst userAgent = await getBrowserUserAgent();\n```\n\n### tc-client-function-get-something-from-dom\n\n```typescript\n// you need to import {ClientFunction} from \"testcafe\";\n// this sample will get the details of a selected input\n// see http://devexpress.github.io/testcafe/example/\n// \u003clabel for=\"windows\"\u003e\n//     \u003cinput type=\"radio\" name=\"os\" id=\"windows\" value=\"Windows\"\u003e\n//     Windows\n// \u003c/label\u003e\nconst inputSelector = Selector('label[for=\"windows\"] input');\nconst getInputDetails = ClientFunction((selector: Selector) =\u003e {\n    return new Promise( (resolve) =\u003e {\n        const element: any = selector();\n        // check, in developper tools, what are the available properties in element\n        // tslint:disable-next-line:no-console\n        console.log(\"element:\", element);\n        resolve({\n            checked: element.checked,\n            disabled: element.disabled,\n            id: element.id,\n            name: element.name,\n            type: element.type,\n            value: element.value,\n        });\n    });\n});\nconst inputDetails = await getInputDetails(inputSelector);\n```\n\n### tc-client-function-get-style-attribute\n\n```typescript\n// you need to import {ClientFunction} from 'testcafe';\n// get style attribute of a Selector\n// see http://devexpress.github.io/testcafe/example/\nconst getStyleAttributeOf = ClientFunction((selector: Selector) =\u003e {\n    const element = selector();\n    return element.getAttribute('style');\n});\n\nconst field = Selector('div#slider \u003e span');\nconst styles = await getStyleAttributeOf(field) || '';\nconsole.log(`styles = '${styles}'`);\n```\n\n### tc-client-function-set-style-attribute\n\n```typescript\n// you need to import {ClientFunction} from 'testcafe';\n// get style attribute of a Selector\n// see http://devexpress.github.io/testcafe/example/\nconst setStyleAttributeOf = ClientFunction((selector: Selector, styleValue: string) =\u003e {\n    const element: any = selector();\n    element.setAttribute('style', styleValue);\n});\n\nconst field = Selector('div#slider \u003e span');\nconst newStyles = 'left: 50%;';\nawait setStyleAttributeOf(field, newStyles);\n```\n\n### tc-client-function-get-window-state\n\n```typescript\n// you need to import {ClientFunction} from \"testcafe\";\nconst getWindowState = ClientFunction(() =\u003e ({\n    height:      window.innerHeight,\n    isMaximized: window.outerWidth \u003e= window.screen.availWidth \u0026\u0026 window.outerHeight \u003e=window.screen.availHeight,\n    width:       window.innerWidth,\n}));\nconst windowState = await getWindowState();\n```\n\n### tc-client-function-measure-execution-time\n\n```typescript\n// you need to import {ClientFunction} from \"testcafe\";\nconst stopWatch = {\n    elapsedTimeInMilliseconds: ClientFunction(() =\u003e Date.now() - (window as any).startTime),\n    start: ClientFunction(() =\u003e (window as any).startTime = Date.now()),\n};\nawait stopWatch.start();\n// place here the code to instrument,\nconst elapsed = await stopWatch.elapsedTimeInMilliseconds();\nawait t.expect(elapsed).lt(1000);\n```\n\n### tc-client-function-read-localstorage\n\n```typescript\n// you need to import {ClientFunction} from \"testcafe\";\nconst getLocalStorageValueByKey = ClientFunction((key: string) =\u003e {\n    return new Promise( (resolve) =\u003e {\n        const result = localStorage.getItem(key);\n        resolve(result);\n    });\n});\nconst value = await getLocalStorageValueByKey(\"mykey\");\n```\n\n### tc-client-function-write-to-localstorage\n\n```typescript\n// you need to import {ClientFunction} from \"testcafe\";\nconst setLocalStorage = ClientFunction((key: string, value: string) =\u003e {\n    return new Promise( (resolve, reject) =\u003e {\n        try {\n            localStorage.setItem(key, value);\n            resolve();\n        } catch (error) {\n            reject(error);\n        }\n    });\n});\nawait setLocalStorage(\"mykey\", \"myValue\");\n```\n\n### tc-client-function-scroll-to-element\n\n```typescript\n// you need to import {ClientFunction} from \"testcafe\";\n// this sample will scroll to a label\n// see http://devexpress.github.io/testcafe/example/\n// \u003clabel for=\"windows\"\u003e\n//     \u003cinput type=\"radio\" name=\"os\" id=\"windows\" value=\"Windows\"\u003e\n//     Windows\n// \u003c/label\u003e\nconst inputSelector = Selector('label[for=\"windows\"]');\nconst scrollToElement = ClientFunction((selector: Selector, offset: {x: number, y: number}) =\u003e {\n    return new Promise( (resolve) =\u003e {\n        const element: any = selector();\n        if (element \u0026\u0026 element.scrollIntoView) {\n            element.scrollIntoView();\n        }\n        // do a small shift up and left\n        if (window \u0026\u0026 window.scrollBy \u0026\u0026 offset) {\n            window.scrollBy(offset.x, offset.y);\n        }\n        resolve();\n    });\n});\nawait scrollToElement(inputSelector, {x: 20, y: -20});\n```\n\n### tc-client-function-set-something-in-dom\n\n```typescript\n// you need to import {ClientFunction} from \"testcafe\";\n// this sample will replace a checkbox label\n// see http://devexpress.github.io/testcafe/example/\n// \u003clabel for=\"windows\"\u003e\n//     \u003cinput type=\"radio\" name=\"os\" id=\"windows\" value=\"Windows\"\u003e\n//     Windows\n// \u003c/label\u003e\nconst mySelector = Selector('label[for=\"windows\"]');\nconst setLabel = ClientFunction((selector: Selector, value: string) =\u003e {\n    const element: any = selector();\n    // check, in developper tools, what are the available properties in element\n    // tslint:disable-next-line:no-console\n    console.log(\"element:\", element);\n    element.firstElementChild.nextSibling.replaceWith(value);\n});\nawait setLabel(mySelector, \"Windows 10\");\n```\n\n### tc-copy-paste-text\n\n```typescript\n// see http://devexpress.github.io/testcafe/example/\nconst input = Selector('input#developer-name[type=\"text\"]');\nawait t // copy paste a text in an input box and press tab\n    .setTestSpeed(0.7)\n    .hover(input)\n    .expect(input.hasAttribute(\"disabled\")).notOk({timeout: 5000})\n    .click(input)\n    .typeText(input, \"john doe\", {replace: true, paste: true})\n    .pressKey(\"tab\");\n```\n\n### tc-ensure-field-is-ready-before-clicking-on-it\n\n```typescript\n// Ensure field is ready before clicking on it\n// see http://devexpress.github.io/testcafe/example/\nconst field = Selector('input#developer-name[type=\"text\"]');\nawait t\n    .expect(field.with({visibilityCheck: true}).exists)\n    .ok({timeout: 5000})\n    .hover(field)\n    .expect(field.hasAttribute('disabled'))\n    .notOk({timeout: 5000});\n```\n\n### tc-filter-hidden-elements\n\n```typescript\n// get all hidden inputs\n// see http://devexpress.github.io/testcafe/example/\nconst inputs = Selector(\"input\");\nconst hiddenInputs =  inputs.filterHidden(); // v0.19.0\nawait t.expect(hiddenInputs.count).eql(1);\nconsole.log(`first hiddenInput is '${await hiddenInputs.nth(0).id}'`);\n```\n\n### tc-filter-visible-elements\n\n```typescript\n// get all visible inputs\n// see http://devexpress.github.io/testcafe/example/\nconst inputs = Selector(\"input\");\nconst visibleInputs = inputs.filterVisible(); // v0.19.0\nawait t.expect(visibleInputs.count).eql(11);\nconsole.log(`first visibleInputs is '${await visibleInputs.nth(0).id}'`);\n```\n\n### tc-fixture-with-start-page\n\n```typescript\nfixture(\"My Fixture\")\n    .page(\"http://myurl\");\n\n```\n\n### tc-fixture-with-start-page-and-hooks\n\n```typescript\nfixture(\"My Fixture\")\n    .page(\"http://myurl\")\n    .before(async (ctx) =\u003e {\n        // inject in the fixture context any object you want to share beetween tests\n        ctx.config = config;\n    })\n    .beforeEach(async (t) =\u003e {\n        // inject in the test context any input data needed to run the test\n        t.ctx.inputData = inputData;\n        // put here all actions that are common to all tests\n});\n```\n\n### tc-get-selected-option\n\n```typescript\n// get the selected option\n// see http://devexpress.github.io/testcafe/example/\nconst select = Selector(\"select#preferred-interface\");\nconst selectedOption = select\n        .find(\"option\")\n            .filter((node) =\u003e {\n                const option = node as HTMLOptionElement;\n                if (option \u0026\u0026 option.selected) {\n                    return true;\n                }\n                return false;\n            })\n            .nth(0);\nconst selectedOptionContent = await  selectedOption.textContent;\n```\n\n### tc-import\n\n```typescript\nimport \"testcafe\";\nimport {ClientFunction, Selector} from \"testcafe\";\n```\n\n### tc-iterate-over-selected-checkboxes\n\n```typescript\n// iterate over selected checkboxes\n// see http://devexpress.github.io/testcafe/example/\nconst selectedCheckboxes = Selector('input[type=\"checkbox\"]')\n    // select all checboxes whose name value is in a set of predefined values\n    .withAttribute(\"name\", /custom-name|remote|re-using|background|CI|analysis/)\n        .filter((node) =\u003e {\n            const checkbox = node as HTMLInputElement;\n            if (checkbox \u0026\u0026 checkbox.checked) {\n                return true;\n            }\n            return false;\n        });\nconst checkedCount = await selectedCheckboxes.count;\nconst checkedIds = [];\nfor (let i = 0; i \u003c checkedCount; i++) {\n    checkedIds.push(await selectedCheckboxes.nth(i).id);\n}\n// now you can make your business check from the checkedIds array\n```\n\n### tc-maximize-window\n\n```js\nawait t // set the window size to it's max size\n    .maximizeWindow();\n```\n\n### tc-navigate-to-url\n\n```js\nawait t // navigate to url\n    .navigateTo(\"url\");\n```\n\n### tc-pause-test-for-client-side-debugging\n\n```js\nawait t.debug();\n```\n\n### tc-reload-browser\n\n```js\n// you need to import {ClientFunction} from \"testcafe\";\nconst reloadBrowser = ClientFunction(() =\u003e window.location.reload(true));\nawait reloadBrowser();\n```\n\n### tc-remove-text\n\n```js\n// see http://devexpress.github.io/testcafe/example/\nconst input = Selector('input#developer-name[type=\"text\"]');\nawait t // remove the text present in an input box and press tab\n    .setTestSpeed(0.7)\n    .hover(input)\n    .expect(input.hasAttribute(\"disabled\")).notOk({timeout: 5000})\n    .click(input)\n    .pressKey(\"ctrl+a delete\")\n    .pressKey(\"tab\");\n```\n\n### tc-selector-with-options\n\n```js\n// see http://devexpress.github.io/testcafe/example/\nconst mySelector = Selector('input#developer-name')\n    .with({timeout: 5000, visibilityCheck: true})\n    .nth(0);\n```\n\n### tc-select-an-option-by-content\n\n```js\n// see http://devexpress.github.io/testcafe/example/\nconst select = Selector(\"select#preferred-interface\");\nawait t // select an option by its content and press tab\n    .setTestSpeed(0.7)\n    .hover(select)\n    .expect(select.hasAttribute(\"disabled\")).notOk({timeout: 5000})\n    .click(select)\n    .click(select\n        .find(\"option\")\n        .withText(\"Commmand Line\")\n        .nth(0))\n    .pressKey(\"tab\");\n```\n\n### tc-select-an-option-by-content-with-regex\n\n```js\n// see http://devexpress.github.io/testcafe/example/\nconst select = Selector(\"select#preferred-interface\");\nawait t // select an option by content with a Regex and press tab\n    .setTestSpeed(0.7)\n    .hover(select)\n    .expect(select.hasAttribute(\"disabled\")).notOk({timeout: 5000})\n    .click(select)\n    .click(select\n        .find(\"option\")\n        .withText(new RegExp(`^.*API$`))\n        .nth(0))\n    .pressKey(\"tab\");\n```\n\n### tc-select-an-option-by-exact-content\n```js\n// see http://devexpress.github.io/testcafe/example/\n    const select = Selector(\"select#preferred-interface\");\n    await t // select an option by its exact content and press tab\n        .setTestSpeed(0.7)\n        .hover(select)\n        .expect(select.hasAttribute(\"disabled\")).notOk({timeout: 5000})\n        .click(select)\n        .click(select\n            .find(\"option\")\n            .withExactText(\"JavaScript API\")\n            .nth(0))\n        .pressKey(\"tab\");\n```\n\n### tc-select-a-radio-button-by-value\n\n```typescript\n// see http://devexpress.github.io/testcafe/example/\n// select a radio button by it's input value\nconst radioButtonValue = \"Linux\"; // the value to search\nconst radioButton = Selector('input[type=\"radio\"]')\n    .withAttribute(\"name\", \"os\") // select all radio buttons within the group named 'os'\n        .filter((node) =\u003e {\n            const button = node as HTMLInputElement;\n            if (button \u0026\u0026 button.value === radioButtonValue) {\n                return true;\n            }\n            return false;\n        }, {radioButtonValue})\n        .nth(0);\nawait t\n    .hover(radioButton)\n    .expect(radioButton.hasAttribute(\"disabled\")).notOk({timeout: 5000})\n    .click(radioButton)\n    .pressKey(\"tab\");\n```\n\n### tc-select-first-non-empty-option\n\n```typescript\n// select first non-empty option\nconst selector = Selector(\"select\").nth(0);\nconst firstNonEmptyOption = selector\n    .find(\"option\")\n        .filter((node) =\u003e {\n            const option = node as HTMLOptionElement;\n            if (option \u0026\u0026 option.innerText \u0026\u0026 option.innerText.trim() !== \"\") {\n                return true;\n            }\n            return false;\n        })\n        .nth(0);\nawait t\n    .hover(selector)\n    .click(selector)\n    .click(firstNonEmptyOption);\n```\n\n### tc-select-first-option\n\n```typescript\n// see http://devexpress.github.io/testcafe/example/\nconst select = Selector(\"select#preferred-interface\");\nawait t // select the first option and press tab\n    .setTestSpeed(0.7)\n    .hover(select)\n    .expect(select.hasAttribute(\"disabled\")).notOk({timeout: 5000})\n    .click(select)\n    .click(select\n        .find(\"option\")\n        .nth(0))\n    .pressKey(\"tab\");\n```\n\n### tc-select-last-option\n\n```typescript\n// see http://devexpress.github.io/testcafe/example/\nconst select = Selector(\"select#preferred-interface\");\nawait t // select the last option and press tab\n    .setTestSpeed(0.7)\n    .hover(select)\n    .expect(select.hasAttribute(\"disabled\")).notOk({timeout: 5000})\n    .click(select)\n    .click(select\n        .find(\"option\")\n        .nth(-1))\n    .pressKey(\"tab\");\n```\n\n### tc-set-window-size-to-custom-width-and-height\n\n```js\nawait t // set the window size\n    .resizeWindow(1024, 600);\n```\n\n### tc-set-window-size-to-fit-device\n\n```js\nawait t // set the window size to fit specific device (see: http://viewportsizes.com/)\n    .resizeWindowToFitDevice(\"Galaxy Nexus\", {portraitOrientation: true});\n```\n\n### tc-take-screenshot-of-an-element-in-dom\n\n```js\n// see http://devexpress.github.io/testcafe/example/\n// you need to set the command-line option --screenshots \u003cdir\u003e\nconst input = Selector('input#developer-name[type=\"text\"]');\nawait t\n    .hover(input)\n    .expect(input.hasAttribute(\"disabled\")).notOk({timeout: 5000})\n    .click(input)\n    .typeText(input, \"john doe\", {replace: true})\n    .takeElementScreenshot(input,\n        // store the screenshot in the --screenshots dir\n        \"screenshot1.png\", {\n        includeMargins: true,\n        includePaddings: true,\n    });\n```\n\n### tc-test\n\n```js\ntest(\"My Test\", async (t) =\u003e {\n    \n});\n```\n\n### tc-test-with-hooks\n\n```js\ntest(\"My Test\", async (t) =\u003e {\n    // test code ommited for brevity\n    })\n    .before(async (t) =\u003e {\n        // inject in the test context any input data needed to run this specific test\n        t.ctx.inputData = getSomeData();\n    })\n    .after(async (t) =\u003e {\n        // test finalization code\n    });\n```\n\n### tc-type-text\n\n```js\n// see http://devexpress.github.io/testcafe/example/\nconst input = Selector(\"input#developer-name\");\nawait t // type a text in an input box and press tab\n    .setTestSpeed(0.7)\n    .hover(input)\n    .expect(input.hasAttribute(\"disabled\")).notOk({timeout: 5000})\n    .click(input)\n    .typeText(input, \"john doe\", {replace: true})\n    .pressKey(\"tab\");\n```\n\n### tc-type-text-letter-by-letter\n\n```js\n// Type text letter by letter like a real user\n// usefull when you want to test the behavior of autocomplete fields\n// see http://devexpress.github.io/testcafe/example/\nconst selector = Selector('input#developer-name[type=\"text\"]');\nconst letters = [...'john doe'];\nlet index = -1;\nfor (const letter of letters) {\n    index += 1;\n    if (index === 0) {\n        await t.typeText(selector,letter, {replace: true});\n        continue;\n    }\n    await t\n        .wait(100)\n        .typeText(selector,letter);\n}\n```\n\n### tc-wait-for-a-selector-to-appear\n\n```js\n// wait for a selector to appear\nconst selector = Selector(\"div.popup\")\n    .with({visibilityCheck: true})\n    .nth(0);\nawait t\n    .expect(selector.exists).ok({timeout: 5000});\n```\n\n### tc-wait-for-a-selector-to-disappear\n\n```js\n// wait for a selector to disappear\nconst spinner = Selector(\"div.loading\");\nawait t\n    .expect(spinner.with({visibilityCheck: true}).exists).notOk({timeout: 5000});\n\n```\n\n### tc-wait-until-exists-property-of-selector-is-stable\n\n```js\n// wait until the 'exists' property of a selector is stable\n// see http://devexpress.github.io/testcafe/example/\nconst mySelector = Selector(\"select#preferred-interface\");\nawait wait(2000).until(mySelector).exists.isStable();\n// now it is safe to evaluate the exists property\nconst exists = await mySelector.exists;\n```\n\n`wait` function\n\n```ts\n/**\n * waiting for selector stability\n * @param {number} timeout : amount of time in milliseconds during which a selector property must be stable\n */\nexport function wait(timeout: number) {\n    return {\n         until: (selector: Selector) =\u003e {\n            return {\n                /**\n                 * exists property of selector\n                 */\n                exists:  {\n                    /**\n                     * wait until exists property of selector is stable\n                     */\n                    isStable: async (): Promise\u003cvoid\u003e =\u003e {\n                        const interval = 100;\n                        const elapsedTimeMaxValue = timeout * 3;\n                        let stabilityElapsedTime = 0;\n                        let previousValue = \"\";\n                        let elapsedTime = 0;\n                        while (true) {\n                            await t.wait(interval);\n                            const currentValue = (await selector.exists).toString();\n                            // tslint:disable-next-line:no-console\n                            console.log(`Selector exists property evaluates to '${currentValue}'`);\n                            if (currentValue !== previousValue) {\n                                stabilityElapsedTime = 0;\n                            }\n                            if (currentValue === previousValue) {\n                                stabilityElapsedTime += interval;\n                            }\n                            previousValue = currentValue;\n                            elapsedTime += interval;\n                            if (stabilityElapsedTime \u003e timeout) {\n                                // tslint:disable-next-line:no-console\n                                console.log(`Now it is safe to check if selector exists`);\n                                return;\n                            }\n                            if (elapsedTime \u003e elapsedTimeMaxValue) {\n                                // tslint:disable-next-line:no-console\n                                console.log(`Selector is unstable`);\n                                return;\n                            }\n                        }\n                    },\n                },\n            };\n        },\n    };\n}\n```","funding_links":[],"categories":["vscode-extension"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhdorgeval%2Ftestcafe-snippets","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhdorgeval%2Ftestcafe-snippets","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhdorgeval%2Ftestcafe-snippets/lists"}