Best JavaScript code snippet using testcafe
test.js
Source:test.js
2import { Selector, ClientFunction } from 'testcafe';3fixture `Modal`4 .page `./test.html`;5test('Build a modal without a title and message', async (t) => {6 await ClientFunction(() => {7 return phonon.modal().show();8 })();9 await t10 .wait(1000)11 .expect(Selector('.modal.show').exists).ok()12 .expect(Selector('.modal.show .modal-title').innerText).eql('')13 .expect(Selector('.modal.show .modal-body').innerText).eql('')14 .click('.modal.show .btn-primary')15 .wait(1000)16 .expect(Selector('.modal.show').exists).notOk();17});18test('Build the same modal with jQuery', async (t) => {19 await ClientFunction(() => {20 return $().modal().show();21 })();22 await t23 .wait(1000)24 .expect(Selector('.modal.show').exists).ok()25 .expect(Selector('.modal.show .modal-title').innerText).eql('')26 .expect(Selector('.modal.show .modal-body').innerText).eql('')27 .click('.modal.show .btn-primary')28 .wait(1000)29 .expect(Selector('.modal.show').exists).notOk();30});31test('Build a modal with a title and a message', async (t) => {32 const title = 'My Title';33 const message = 'My message';34 await ClientFunction((title, message) => {35 return phonon.modal({ title, message }).show();36 })(title, message);37 await t38 .wait(1000)39 .expect(Selector('.modal.show .modal-title').innerText).eql(title)40 .expect(Selector('.modal.show .modal-body p').innerText).eql(message)41 .click('.modal.show .btn-primary')42 .wait(1000)43 .expect(Selector('.modal.show').exists).notOk();44});45test('Build a modal with a title, a message and custom buttons', async (t) => {46 const title = 'My Title';47 const message = 'My message';48 const eventName = 'myEvent';49 const buttons = [50 {51 event: eventName,52 text: 'Custom button',53 dismiss: true,54 class: 'btn btn-primary',55 },56 ];57 // await t.eval(new Function(`phonon.modal({title: "${title}", message: "${message}", buttons: ${JSON.stringify(buttons)}}).show();`))58 await ClientFunction((title, message, buttons) => {59 return phonon.modal({ title, message, buttons }).show();60 })(title, message, buttons);61 await t62 .wait(1000)63 .expect(Selector('.modal.show .modal-title').innerText).eql(title)64 .expect(Selector('.modal.show .modal-body p').innerText).eql(message)65 .expect(Selector(`.modal-footer [data-event="${eventName}"]`).innerText).eql('Custom button')66 // close the modal with the custom button67 .click(`.modal-footer [data-event="${eventName}"]`)68 .wait(1000)69 .expect(Selector('.modal.show').exists).notOk();70});71test('Show a modal from a button', async (t) => {72 const title = 'Modal title';73 const message = 'Modal body text goes here.';74 await t75 .click('[data-target="#exampleModal"]')76 .wait(1000)77 .expect(Selector('.modal.show .modal-title').innerText).eql(title)78 .expect(Selector('.modal.show .modal-body p').innerText).eql(message)79 .click('.modal.show .btn-primary')80 .wait(1000)81 .expect(Selector('.modal.show').exists).notOk();82});83test('Close a cancelable modal with Escape key', async (t) => {84 await ClientFunction(() => {85 return phonon.modal().show();86 })();87 await t88 .wait(1000)89 .expect(Selector('.modal.show').exists).ok()90 .expect(Selector('.modal.show .modal-title').innerText).eql('')91 .expect(Selector('.modal.show .modal-body').innerText).eql('')92 .pressKey('esc')93 .wait(1000)94 .expect(Selector('.modal.show').exists).notOk();95});96test('Close a cancelable modal by clicking on the backdrop', async (t) => {97 await ClientFunction(() => {98 return phonon.modal().show();99 })();100 await t101 .wait(1000)102 .expect(Selector('.modal.show').exists).ok()103 .expect(Selector('.modal.show .modal-title').innerText).eql('')104 .expect(Selector('.modal.show .modal-body').innerText).eql('')105 .click('.modal-backdrop', { offsetX: 5, offsetY: 5 })106 .wait(1000)107 .expect(Selector('.modal.show').exists).notOk();108});109test('Test uncancelable modal and then close with a button', async (t) => {110 await ClientFunction(() => {111 return phonon.modal({ cancelable: false }).show();112 })();113 await t114 .wait(1000)115 .expect(Selector('.modal.show').exists).ok()116 .pressKey('esc')117 .wait(1000)118 .expect(Selector('.modal.show').count).eql(1)119 .click('.modal-backdrop', { offsetX: 5, offsetY: 5 })120 .wait(1000)121 .expect(Selector('.modal.show').count).eql(1)122 .click('.modal.show .btn-primary')123 .wait(1000)124 .expect(Selector('.modal.show').exists).notOk();125});126test('Test open 2 modals', async (t) => {127 await ClientFunction(() => {128 phonon.modal().show();129 phonon.modal().show();130 })();131 await t132 .wait(1000)133 .expect(Selector('.modal.show').count).eql(2)134 .click('.modal-backdrop', { offsetX: 5, offsetY: 5 })135 .wait(1000)136 .expect(Selector('.modal.show').count).eql(1)137 .click('.modal.show .btn-primary')138 .wait(1000)139 .expect(Selector('.modal.show').exists).notOk();...
test_testcafe_v0.x.x_clientfunction.js
Source:test_testcafe_v0.x.x_clientfunction.js
1import { ClientFunction, t } from 'testcafe';2fixture `ClientFunction`3 .page `http://localhost:3000/fixtures/api/es-next/client-function/pages/index.html`;4const getLocation = ClientFunction(() => document.location.toString());5const getUserAgent = ClientFunction(() => navigator.userAgent);6test('Dispatch', async() => {7 throw await getUserAgent();8});9// $FlowExpectedError - ClientFunction wants fn10ClientFunction(123)11test('Call with arguments', async() => {12 const getElementText = ClientFunction((className, idx) => {13 return document.querySelectorAll('.' + className)[idx].textContent;14 });15 const answer = await getElementText('answer', 1);16 await t.expect(answer.trim()).eql('42');17});18test('Hammerhead code instrumentation', async() => {19 const location = await getLocation();20 await t.expect(location).eql('http://localhost:3000/fixtures/api/es-next/client-function/pages/index.html');21});22test('Async syntax in ClientFunction', async() => {23 ClientFunction(async() => Promise.resolve());24});25test('Generator in ClientFunction', async() => {26 ClientFunction(function*() {27 yield 1;28 });29});30test('Bind ClientFunction', async t => {31 const boundGetLocation = getLocation.with({boundTestRun: t});32 await boundGetLocation();33});34test('Promises support', async() => {35 var res = await ClientFunction(() => {36 return Promise37 .resolve()38 .then(()=> {39 return new Promise(resolve => {40 window.setTimeout(() => resolve(42), 100);41 });42 });43 })();44 await t.expect(res).eql(42);45});46const selectByClassName = ClientFunction(className => document.querySelectorAll('.' + className));47const nthByClass = ClientFunction((className, n) => selectByClassName(className).then(res => res[n]), {dependencies: {selectByClassName}});48test('ClientFunction call with complex argument types', async() => {49 const fn = ClientFunction((re, err, undef, nan) => {50 return re instanceof RegExp &&51 re.source === '\\S+' &&52 err instanceof Error &&53 err.message === 'Hey!' &&54 undef === void 0 &&55 isNaN(nan);56 });57 const res = await fn(/\S+/ig, new Error('Hey!'), void 0, NaN);58 await t.expect(res).ok();59});60test('ClientFunction call with complex return types', async() => {61 const fn = ClientFunction(() => {62 return [/\S+/ig, new Error('Hey!'), void 0, NaN];63 });64 const res = await fn();65 await t.expect(res[0].source).eql('\\S+');66 await t.expect(res[1].message).eql('Hey!');67 await t.expect(res[2]).eql(void 0);68 await t.expect(Number.isNaN(res[3])).ok();69});70test('ClientFunction with function argument', async() => {71 function getAnswer() {72 return new Promise(resolve => {73 setTimeout(() => resolve(42), 30);74 });75 }76 const hfn = ClientFunction(fn => fn());77 const answer = await hfn(getAnswer);78 await t.expect(answer).eql(42);79});80test('Async/await in function argument of ClientFunction', async() => {81 const hfn = ClientFunction(fn => fn());82 await hfn(async() => Promise.resolve());83});84test('ClientFunction with ClientFunction argument', async() => {85 const hfn = ClientFunction(fn => fn());86 const location = await hfn(getLocation);87 await t.expect(location).eql('http://localhost:3000/fixtures/api/es-next/client-function/pages/index.html');88});89test('ClientFunction without `await`', async() => {90 getLocation();91});92test('DOM node return value', async() => {93 const getSomeNodes = ClientFunction(() => {94 const answer = document.querySelector('.answer');95 return [answer ? answer.childNodes[0] : null, document];96 });97 await getSomeNodes();...
init.js
Source:init.js
...9const HPP_API_KEY =10 process.env.HPP_API_KEY ||11 "pk_test_yNznq07p7MChOL8shs7WT3Yat6ZnlqyXq8ep6WKF998";12const mlPage = new ListPage();13const intitWidget = ClientFunction(14 () => {15 window.widget.init({16 selector: IFRAME_SELECTOR,17 flow: "iframe",18 public_key: HPP_API_KEY,19 amount: 100,20 currency: "USD",21 baseUrl: HPP_BASE_URL,22 });23 },24 {25 dependencies: { HPP_BASE_URL, HPP_API_KEY, IFRAME_SELECTOR },26 },27);28fixture`Go to page ${APP_TESTING_BASE_URL}, and initialize hpp iframe`29 .page`${APP_TESTING_BASE_URL}`.beforeEach(async t => {30 t.ctx.HPP_BASE_URL = HPP_BASE_URL;31 const initIframe = intitWidget;32 await initIframe();33});34test("Iframe initialized correct", async t => {35 const getLocation = ClientFunction(() => window.location.href);36 await t.expect(Selector("#payment_widget").exists).ok();37 await t38 .setPageLoadTimeout(10000)39 .switchToIframe("#payment_widget")40 .expect(getLocation())41 .contains(`${t.ctx.HPP_BASE_URL}`);42});43test("Checking that methods list exists", async t => {44 await t45 .setPageLoadTimeout(10000)46 .switchToIframe("#payment_widget")47 .expect(Selector(".payment-wrap__items").exists)48 .ok();49});50// CLICK ON BREADCRUMB NEEDED51// test('Click methods and verify every page', async t => {52// await t53// .setPageLoadTimeout(10000)54// .switchToIframe('#payment_widget')55// const getLocation = ClientFunction(() => window.location.href);56// const methodsCount = await mlPage.getMethodsCount();57// const linkToCastegory = Selector('.payment-methods__select-payment-wrap');58// const allOptions = Selector('.select-payment__options li');59// const linkToMain = allOptions.nth(0)60// let list = await mlPage.getMethodsList();61// for (let i = 0; i < methodsCount; i++) {62// const methodSelector = list.nth(i);63// // TODO: Later compare href and window.href with methods that has been selected;64// let href = await methodSelector.getAttribute('href')65// let id = await methodSelector.getAttribute('id')66// await t67// .click(methodSelector)68// .click(linkToCastegory)69// .click(linkToMain)70// }71// });72test(`Check that widget successfully close`, async t => {73 await t.expect(Selector("#payment_widget").exists).ok();74 const removeIframe = ClientFunction(() => {75 window.widget.close({ frameId: "payment_widget" });76 });77 await removeIframe();78 await t.expect(Selector("#payment_widget").exists).notOk();...
settings.js
Source:settings.js
1import { ClientFunction } from 'testcafe';2export const url = 'http://127.0.0.1:5000/testcafe.html';3export const initSurvey = ClientFunction((json, events) => {4 console.error = (msg) => {5 throw new Error(msg);6 };7 console.warn = (msg) => {8 throw new Error(msg);9 };10 console.log('surveyjs console.error and console.warn override');11 Survey.StylesManager.applyTheme('default');12 var model = new Survey.Model(json);13 var surveyComplete = function (model) {14 window.SurveyResult = model.data;15 document.getElementById(16 'surveyResultElement'17 ).innerHTML = JSON.stringify(model.data);18 };19 if (!!events) {20 for (var str in events) {21 model[str].add(events[str]);22 }23 }24 model.onComplete.add(surveyComplete);25 var targetNode = document.querySelector('#surveyElement');26 targetNode.innerHTML = '';27 model.render(targetNode);28 window.survey = model;29});30export const getSurveyResult = ClientFunction(() => {31 var result = window.SurveyResult;32 if (typeof result === 'undefined') {33 return result;34 }35 //clean result object from the vuejs stuff36 return JSON.parse(JSON.stringify(result));37});38export const setOptions = ClientFunction((questionName, modValue) => {39 var targetNode = document.querySelector('#surveyElement');40 var mergeOptions = function (obj1, obj2) {41 for (var attrname in obj2) {42 obj1[attrname] = obj2[attrname];43 }44 };45 var q = survey.getQuestionByName(questionName || 'car');46 mergeOptions(q, modValue);47 survey.render();48});49export const joinElementInnerText = ClientFunction((tagName, index) => {50 let el = document.getElementsByTagName(tagName)[index];51 const spans = el.querySelectorAll('span');52 let res = '';53 for (let i = 0; i < spans.length; i++) {54 var sp = spans[i];55 if (!sp.innerHTML || sp.innerHTML == ' ') continue;56 let childs = sp.getElementsByTagName('span');57 if (childs.length > 0) continue;58 if (!!res) res += ' ';59 res += sp.innerHTML;60 }61 return res;...
helpers.js
Source:helpers.js
...3import rimraf from 'rimraf'4// Get the path to the index page.5export const getBaseUrl = () => '../../app/dist/index.html'6// Get the current page title.7export const getPageTitle = ClientFunction(() => document.title)8// Get the electron user data directory.9export const getUserDataDir = ClientFunction(() => window.Zap.getUserDataDir())10// Kill the client's active lnd instance, if there is one11export const killLnd = ClientFunction(() => window.Zap.killLnd())12// Delete wallets that may have been created in the tests.13export const deleteUserData = ClientFunction(() =>14 window.Zap.deleteLocalWallet({ chain: 'bitcoin', network: 'testnet', wallet: 'wallet-1' })15)16// Delete persistent data from indexeddb.17export const deleteDatabase = ClientFunction(() => window.db.delete())18// Ensure there are no errors in the console.19export const assertNoConsoleErrors = async t => {20 const { error } = await t.getBrowserConsoleMessages()21 await t.expect(error).eql([])22}23// Simple delay.24export const delay = time => new Promise(resolve => setTimeout(() => resolve(), time))25// Clean out test environment.26export const cleanTestEnvironment = async () => {27 await killLnd()28 await delay(3000)29 await killLnd()30 await deleteDatabase()31 await delay(3000)...
test_popupopen.js
Source:test_popupopen.js
1import { Selector } from 'testcafe';2import { ClientFunction } from 'testcafe';3const getAllCharts = ClientFunction(() => allCharts);4const plotTestData = ClientFunction(() => displaySampleData({5 "SampleName": "test_a1",6 "OriginalSampleName": "orig_test_a1",7 "SiteName": "somewhere",8 "Country": "France",9 "Longitude": 10,10 "Latitude": 50,11 "Elevation": "340",12 "Temperature": [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],13 "Precipitation": [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],14 "LocationReliability": "X",15 "LocationNotes": "Actually in Germany",16 "AreaOfSite": "30",17 "ispercent": true,18 "okexcept": "",19 "Id": 1,20 "Selected": false,21 "Edited": false22}));23const getPlottedPollenData = ClientFunction(() => plottedPollenData.test_a1);24const getPollenDiagram = ClientFunction(() => document.getElementById("pollen-diagram-test_a1").innerHTML.trim());25const getClimateDiagram = ClientFunction(() => document.getElementById("climate-diagram-test_a1").innerHTML.trim());26fixture `Page build`27 .page `../index.html?branch=test-data&meta=test.tsv`;28test('Test plotting of the data', async t => {29 // test for the allCharts getting populated, i.e. until initCrossfilter if30 // finished31 await t.expect(getAllCharts()).ok();32 const plotted = await plotTestData();33 await t.expect(getPlottedPollenData()).ok();34 await t.expect(getPollenDiagram()).ok();35 await t.expect(getClimateDiagram()).ok();...
utils.js
Source:utils.js
1import { Selector, ClientFunction } from 'testcafe'2export const getLocation = ClientFunction(() => document.location.pathname)3export const setToken = ClientFunction(token => {4 window.localStorage.setItem('token', token)5 location.reload(true)6})7export const getToken = ClientFunction(() =>8 window.localStorage.getItem('token')9)10export const clearLocalStorage = ClientFunction(() =>11 window.localStorage.clear()12)13export const dataQaSelector = dataQa => Selector(`[data-qa="${dataQa}"]`)14export const dataQaExists = dataQa => dataQaSelector(dataQa).exists15export const randomString = () =>16 Math.random()17 .toString(36)...
client_functions.js
Source:client_functions.js
1import { ClientFunction } from "testcafe";2export const getCurrentUrl = ClientFunction(() => window.location.href);3export const refreshPage = ClientFunction(() => location.reload());4export const getCookies = ClientFunction(() => document.cookie);...
Using AI Code Generation
1import { ClientFunction } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button');5});6const getPageUrl = ClientFunction(() => window.location.href);7test('Check page URL', async t => {8});9const getTitle = ClientFunction(() => document.title);10test('Check page title', async t => {11 .expect(getTitle()).eql('TestCafe Example Page');12});13const getInnerText = ClientFunction(() => document.querySelector('.result-content').innerText);14test('Check result', async t => {15 .expect(getInnerText()).contains('Thank you, John Smith!');16});17const clickOnButton = ClientFunction(() => {18 document.querySelector('#populate').click();19});20test('Check result', async t => {21 .click('#populate')22 .expect(getInnerText()).contains('Thank you, Peter Parker!');23});24const clickOnButton = ClientFunction(() => {25 document.querySelector('#populate').click();26});27test('Check result', async t => {28 .click('#populate')29 .expect(getInnerText()).contains('Thank you, Peter Parker!');30});31const clickOnButton = ClientFunction(() => {32 document.querySelector('#populate').click();33});34test('Check result', async t => {35 .click('#populate')36 .expect(getInnerText()).contains('Thank you, Peter Parker!');37});38const clickOnButton = ClientFunction(() => {39 document.querySelector('#populate').click();40});41test('Check result', async t => {42 .click('#populate')43 .expect(getInnerText()).contains('Thank you, Peter Parker!');44});
Using AI Code Generation
1import { ClientFunction } from 'testcafe';2test('My first test', async t => {3 const getTitle = ClientFunction(() => document.title);4 const title = await getTitle();5 console.log(title);6});7import { Selector } from 'testcafe';8test('My first test', async t => {9 const developerName = Selector('#developer-name');10 .typeText(developerName, 'John Smith')11 .click('#submit-button');12 const articleHeader = await Selector('.result-content').find('h1');13 let headerText = await articleHeader.innerText;14});15import { Selector } from 'testcafe';16test('My first test', async t => {17 const developerName = Selector('#developer-name');18 .expect(developerName.value).eql('', 'input is empty')19 .typeText(developerName, 'Peter Parker')20 .expect(developerName.value).eql('Peter Parker', 'input has been filled');21});22import { Selector } from 'testcafe';23test('My first test', async t => {24 const interfaceSelect = Selector('#preferred-interface');25 const interfaceOption = interfaceSelect.find('option');26 .click(interfaceSelect)27 .click(interfaceOption.withText('Both'))28 .click('#tried-test-cafe');29});30import { Selector } from 'testcafe';31test('My first test', async t => {32 const interfaceSelect = Selector('#preferred-interface');33 const interfaceOption = interfaceSelect.find('option');34 .click(interfaceSelect)35 .click(interfaceOption.withText('Both'))
Using AI Code Generation
1import { Selector, ClientFunction } from 'testcafe';2test('My first test', async t => {3 .click('#populate')4 .click('#submit-button');5 const getLocation = ClientFunction(() => document.location.href);6 await t.expect(getLocation()).contains('thank-you');7});
Using AI Code Generation
1import { ClientFunction } from 'testcafe';2const getPageUrl = ClientFunction(() => window.location.href);3test('My Test', async t => {4 .typeText('#developer-name', 'Peter Parker')5 .click('#tried-test-cafe')6 .click('#submit-button');7 const url = await getPageUrl();8 await t.expect(url).contains('thank-you');9});
Using AI Code Generation
1import { ClientFunction } from 'testcafe';2import { Selector } from 'testcafe';3const getLocation = ClientFunction(() => document.location.href);4test('My first test', async t => {5 .typeText('#developer-name', 'John Smith')6 .click('#submit-button')7 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');8});
Using AI Code Generation
1const { ClientFunction } = require('testcafe');2const getPageUrl = ClientFunction(() => window.location.href);3test('My first test', async t => {4 .typeText('#developer-name', 'John Smith')5 .click('#submit-button');6 const pageUrl = await getPageUrl();7 await t.expect(pageUrl).contains('thank-you');8});
Using AI Code Generation
1import { ClientFunction } from 'testcafe';2test('My Test', async t => {3 const getPageUrl = ClientFunction(() => window.location.href);4 .typeText('#developer-name', 'John Smith')5 .click('#submit-button')6 .expect(getPageUrl()).contains('thank-you');7});
Using AI Code Generation
1import { ClientFunction } from 'testcafe';2test('My Test', async t => {3 const getDocumentLocation = ClientFunction(() => document.location.href);4 console.log(getDocumentLocation());5});6test('My Test', async t => {7 console.log(await t.eval(() => document.location.href));8});9test('My Test', async t => {10 console.log(await t.eval(() => document.location.href));11});12test('My Test', async t => {13 console.log(await t.eval(() => document.location.href));14});15test('My Test', async t => {16 console.log(await t.eval(() => document.location.href));17});18test('My Test', async t => {19 console.log(await t.eval(() => document.location.href));20});21test('My Test', async t => {22 console.log(await t.eval(() => document.location.href));23});24test('My Test', async t => {25 console.log(await t.eval(() => document.location.href));26});27test('My Test', async t => {28 console.log(await t.eval(() => document.location.href));29});30test('My Test', async t => {31 console.log(await t.eval(() => document.location.href));32});33test('My Test', async t => {34 console.log(await t.eval(() => document.location.href));35});36test('My Test', async t => {37 console.log(await t.eval(() => document.location.href));38});39test('My Test', async t => {40 console.log(await t.eval(() => document.location.href));41});42test('My Test', async t => {43 console.log(await t.eval(() => document.location.href));
Using AI Code Generation
1import { ClientFunction } from 'testcafe';2test('Getting the URL of the page', async t => {3 const getUrl = ClientFunction(() => window.location.href);4});5import { ClientFunction } from 'testcafe';6test('Getting the URL of the page', async t => {7 const getUrl = ClientFunction(() => window.location.href);8});9import { ClientFunction } from 'testcafe';10test('Getting the URL of the page', async t => {11 const getUrl = ClientFunction(() => window.location.href);12});13import { ClientFunction } from 'testcafe';14test('Getting the URL of the page', async t => {15 const getUrl = ClientFunction(() => window.location.href);16});17import { ClientFunction } from 'testcafe';18test('Getting the URL of the page', async t => {19 const getUrl = ClientFunction(() => window.location.href);20});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!