Best JavaScript code snippet using testcafe
amp-story-dev-tools-tab-preview.js
Source:amp-story-dev-tools-tab-preview.js
...338 * Eg: `iPhone 11 Pro (Native) -> iphone11pronative`339 * @param {string} name340 * @return {string}341 */342function simplifyDeviceName(name) {343 return name.toLowerCase().replace(/[^a-z0-9]/gi, '');344}345/**346 * Get devices from the element attribute into list of devices.347 *348 * Uses simplifyDeviceName function to match the names passed on the attribute,349 * finding the first device in the list of ALL_DEVICES that starts with the string passed.350 * Eg: `devices="ipad;iphone"` will find the ipad and also the first device in ALL_DEVICES351 * that starts with "iphone" (ignoring case and symbols).352 * @param {string} queryHash353 * @return {Array<*>}354 */355function parseDevices(queryHash) {356 const screenSizes = [];357 queryHash.split(';').forEach((deviceName) => {358 let currSpecs = null;359 currSpecs = ALL_DEVICES.find((el) => {360 // Find first device that has prefix of the device name passed in.361 const currDeviceName = simplifyDeviceName(el.name);362 const specDeviceName = simplifyDeviceName(deviceName);363 return (364 currDeviceName.substring(0, specDeviceName.length) === specDeviceName365 );366 });367 if (currSpecs) {368 screenSizes.push(currSpecs);369 }370 });371 return screenSizes;372}373/** @enum {string} */374const PREVIEW_ACTIONS = {375 SHOW_HELP_DIALOG: 'showHelpDialog',376 SHOW_ADD_DEVICE_DIALIG: 'showAddDeviceDialog',377 CLOSE_DIALOG: 'closeDialog',378 REMOVE_DEVICE: 'removeDevice',379 TOGGLE_DEVICE_CHIP: 'toggleDeviceChip',380};381export class AmpStoryDevToolsTabPreview extends AMP.BaseElement {382 /** @param {!Element} element */383 constructor(element) {384 super(element);385 /** @private {?string} */386 this.storyUrl_ = null;387 /** @private {!Array<DeviceInfo>} */388 this.devices_ = [];389 /** @private {?Element} the current dialog being shown or null if none are active. */390 this.currentDialog_ = null;391 /** @private {!Element} container for the device previews */392 this.devicesContainer_ = null;393 this.onResize_ = this.onResize_.bind(this);394 /** @private {Map<!Element, !Array<string>>} navigation events expected to be received on each player */395 this.expectedNavigationEvents_ = {};396 }397 /** @override */398 isLayoutSupported() {399 return true;400 }401 /** @override */402 buildCallback() {403 this.storyUrl_ = this.element.getAttribute('data-story-url');404 this.element.classList.add('i-amphtml-story-dev-tools-tab');405 this.devicesContainer_ = htmlFor(406 this.element407 )`<div class="i-amphtml-story-dev-tools-devices-container"></div>`;408 this.element.appendChild(this.devicesContainer_);409 const chipListContainer = this.element.ownerDocument.createElement('div');410 chipListContainer.classList.add(411 'i-amphtml-story-dev-tools-device-chips-container'412 );413 this.element.appendChild(chipListContainer);414 const chipList = this.element.ownerDocument.createElement('span');415 chipList.classList.add('i-amphtml-story-dev-tools-device-chips');416 chipListContainer.appendChild(chipList);417 chipListContainer.appendChild(this.buildAddDeviceButton_());418 chipListContainer.appendChild(this.buildHelpButton_());419 }420 /** @override */421 layoutCallback() {422 parseDevices(423 this.element.getAttribute('data-devices') || DEFAULT_DEVICES424 ).forEach((device) => {425 this.addDevice_(device.name);426 });427 this.repositionDevices_();428 this.element.addEventListener('click', (e) => this.handleTap_(e.target));429 observeContentSize(this.element, this.onResize_);430 }431 /**432 * Builds the add device button433 * @private434 * @return {!Element}435 */436 buildAddDeviceButton_() {437 const addDeviceButton = buildDeviceChipTemplate(this.element);438 addDeviceButton.classList.add('i-amphtml-story-dev-tools-add-device');439 addDeviceButton.classList.add('i-amphtml-story-dev-tools-button');440 addDeviceButton.setAttribute(441 'data-action',442 PREVIEW_ACTIONS.SHOW_ADD_DEVICE_DIALIG443 );444 addDeviceButton.querySelector(445 '.i-amphtml-story-dev-tools-device-chip-name'446 ).textContent = 'ADD DEVICE';447 return addDeviceButton;448 }449 /**450 * Builds the add device button451 * @private452 * @return {!Element}453 */454 buildHelpButton_() {455 const addHelpButton = buildHelpButtonTemplate(this.element);456 addHelpButton.setAttribute('data-action', PREVIEW_ACTIONS.SHOW_HELP_DIALOG);457 return addHelpButton;458 }459 /**460 * Creates a device layout for preview461 * @private462 * @param {!DeviceInfo} device463 * @return {!Element}464 */465 buildDeviceLayout_(device) {466 const deviceLayout = buildDeviceTemplate(this.element);467 device.details.forEach((detail) => deviceLayout.setAttribute(detail, ''));468 const devicePlayer = deviceLayout.querySelector('amp-story-player');469 devicePlayer.setAttribute('width', device.width);470 devicePlayer.setAttribute('height', device.height);471 const storyA = devicePlayer.querySelector('a');472 storyA.textContent = 'Story 1';473 storyA.href = this.storyUrl_;474 setStyles(devicePlayer, {475 width: device.width + 'px',476 height: device.height + 'px',477 });478 setStyles(479 deviceLayout.querySelector('.i-amphtml-story-dev-tools-device-screen'),480 {481 height: device.deviceHeight482 ? device.deviceHeight + 'px'483 : 'fit-content',484 }485 );486 device.player = new AmpStoryPlayer(this.win, devicePlayer);487 return deviceLayout;488 }489 /**490 * @private491 * @param {!Element} targetElement492 */493 handleTap_(targetElement) {494 const actionElement = closest(495 targetElement,496 (el) => el.hasAttribute('data-action'),497 this.element498 );499 if (!actionElement || actionElement.hasAttribute('disabled')) {500 return;501 }502 switch (actionElement.getAttribute('data-action')) {503 case PREVIEW_ACTIONS.SHOW_HELP_DIALOG:504 this.showHelpDialog_();505 break;506 case PREVIEW_ACTIONS.SHOW_ADD_DEVICE_DIALIG:507 this.showAddDeviceDialog_();508 break;509 case PREVIEW_ACTIONS.CLOSE_DIALOG:510 this.hideCurrentDialog_();511 break;512 case PREVIEW_ACTIONS.REMOVE_DEVICE:513 case PREVIEW_ACTIONS.TOGGLE_DEVICE_CHIP:514 this.onDeviceChipToggled_(actionElement);515 break;516 }517 }518 /**519 * @private520 * @param {string} deviceName521 */522 addDevice_(deviceName) {523 const deviceSpecs = ALL_DEVICES.find((d) => d.name === deviceName);524 if (!deviceSpecs) {525 return;526 }527 const deviceLayout = this.buildDeviceLayout_(deviceSpecs, this.storyUrl_);528 deviceSpecs.element = deviceLayout;529 deviceSpecs.chip = this.buildDeviceChip_(deviceSpecs.name);530 this.mutateElement(() => {531 this.devicesContainer_.appendChild(deviceLayout);532 this.element533 .querySelector('.i-amphtml-story-dev-tools-device-chips')534 .appendChild(deviceSpecs.chip);535 }).then(() => {536 deviceSpecs.player537 .getElement()538 .addEventListener('storyNavigation', (event) =>539 this.onPlayerNavigation_(event, deviceSpecs)540 );541 deviceSpecs.player.load();542 });543 this.expectedNavigationEvents_[deviceSpecs.name] = [];544 this.devices_.push(deviceSpecs);545 this.updateDevicesInHash_();546 }547 /**548 * Triggered when a player emits a storyNavigationEvent.549 *550 * A navigation event from a player can come from a user interaction or a previous programmatic call.551 * Expected navigation events from programmatic calls are stored in `this.expectedNavigationEvents_`,552 * so they should not be propagated (but deleted from the list of expected events).553 *554 * Behavior of expectedNavigationEvents:555 * - If an event was not expected, it means it was user navigation and should be propagated to other players.556 * - If an event was expected, sync the expected list up to that page by removing all the pages expected557 * up to the one received in the navigation event. This clears any events that could be dispatched when the story558 * was loading and never were executed.559 *560 * @param {!Event} event561 * @param {!DeviceInfo} deviceSpecs562 * @private563 */564 onPlayerNavigation_(event, deviceSpecs) {565 const {pageId} = event.detail;566 const pageIndexInExpectedList =567 this.expectedNavigationEvents_[deviceSpecs.name].lastIndexOf(pageId);568 if (pageIndexInExpectedList > -1) {569 // Remove the expected events up to the most recently received event if it was in the list.570 this.expectedNavigationEvents_[deviceSpecs.name].splice(571 0,572 pageIndexInExpectedList + 1573 );574 return;575 }576 this.devices_.forEach((d) => {577 if (d != deviceSpecs) {578 d.player.show(/* storyUrl */ null, event.detail.pageId);579 this.expectedNavigationEvents_[d.name].push(pageId);580 }581 });582 }583 /**584 * Try to remove a device with the name passed.585 * @private586 * @param {string} deviceName587 * @return {bool} whether a device was found and removed with that name.588 */589 removeDevice_(deviceName) {590 const device = this.devices_.find((d) => d.name === deviceName);591 if (device) {592 this.mutateElement(() => {593 device.chip.remove();594 device.element.remove();595 });596 this.devices_ = this.devices_.filter((d) => d != device);597 delete this.expectedNavigationEvents_[device.name];598 this.updateDevicesInHash_();599 return true;600 }601 return false;602 }603 /**604 * @param {string} deviceName605 * @return {!Element} the device chip606 */607 buildDeviceChip_(deviceName) {608 const deviceChip = buildDeviceChipTemplate(this.element);609 deviceChip.querySelector(610 '.i-amphtml-story-dev-tools-device-chip-name'611 ).textContent = deviceName;612 deviceChip.setAttribute('data-action', PREVIEW_ACTIONS.REMOVE_DEVICE);613 deviceChip.setAttribute('data-device', deviceName);614 return deviceChip;615 }616 /**617 * @param {!Element} chipElement618 * @private619 */620 onDeviceChipToggled_(chipElement) {621 const deviceName = chipElement.getAttribute('data-device');622 if (this.removeDevice_(deviceName)) {623 this.mutateElement(() => {624 chipElement.setAttribute('inactive', '');625 this.toggleDeviceChipsWithSpaceAvailable_();626 });627 } else {628 this.mutateElement(() => {629 chipElement.removeAttribute('inactive');630 this.toggleDeviceChipsWithSpaceAvailable_();631 });632 this.addDevice_(deviceName);633 }634 this.repositionDevices_();635 }636 /**637 * If the devices are not the default ones, add them to the hashString638 * @private639 */640 updateDevicesInHash_() {641 const devicesStringRepresentation = this.devices_642 .map((device) => simplifyDeviceName(device.name))643 .join(';');644 this.element.setAttribute('data-devices', devicesStringRepresentation);645 updateHash(646 {647 'devices':648 devicesStringRepresentation != DEFAULT_DEVICES649 ? devicesStringRepresentation650 : null,651 },652 this.win653 );654 }655 /**656 * Recalculate the positions of the devices to keep them spaced and scaled evenly....
config.js
Source:config.js
...30function simplifyDeviceName (deviceName) {31 return deviceName.replace(/\s/g, '').toLowerCase();32}33function findDevice (deviceName) {34 var simpleName = simplifyDeviceName(deviceName);35 return emulatedDevices.filter(device => simplifyDeviceName(device.title).indexOf(simpleName) >= 0)[0];36}37function getDeviceBasedOptions (deviceName, orientation) {38 if (!deviceName)39 return {};40 var deviceData = findDevice(deviceName);41 if (!deviceData)42 return {};43 var mobile = deviceData.capabilities.indexOf('mobile') >= 0;44 if (!orientation)45 orientation = mobile ? 'vertical' : 'horizontal';46 return {47 mobile: mobile,48 orientation: orientation,49 touch: deviceData.capabilities.indexOf('touch') >= 0,...
Using AI Code Generation
1import {simplifyDeviceName} from 'testcafe-browser-tools';2test('My Test', async t => {3 .expect(simplifyDeviceName('iPhone 6')).eql('iPhone 6')4 .expect(simplifyDeviceName('iPhone 6 Plus')).eql('iPhone 6 Plus')5 .expect(simplifyDeviceName('iPhone 6s')).eql('iPhone 6s')6 .expect(simplifyDeviceName('iPhone 6s Plus')).eql('iPhone 6s Plus')7 .expect(simplifyDeviceName('iPhone 7')).eql('iPhone 7')8 .expect(simplifyDeviceName('iPhone 7 Plus')).eql('iPhone 7 Plus')9 .expect(simplifyDeviceName('iPhone 8')).eql('iPhone 8')10 .expect(simplifyDeviceName('iPhone 8 Plus')).eql('iPhone 8 Plus')11 .expect(simplifyDeviceName('iPhone X')).eql('iPhone X')12 .expect(simplifyDeviceName('iPhone XS')).eql('iPhone XS')13 .expect(simplifyDeviceName('iPhone XS Max')).eql('iPhone XS Max')14 .expect(simplifyDeviceName('iPhone XR')).eql('iPhone XR')15 .expect(simplifyDeviceName('iPhone 11')).eql('iPhone 11')16 .expect(simplifyDeviceName('iPhone 11 Pro')).eql('iPhone 11 Pro')17 .expect(simplifyDeviceName('iPhone 11 Pro Max')).eql('iPhone 11 Pro Max')18 .expect(simplifyDeviceName('iPhone SE')).eql('iPhone SE')19 .expect(simplifyDeviceName('iPhone SE (2nd generation)')).eql('iPhone SE')20 .expect(simplifyDeviceName('iPhone 12')).eql('iPhone 12')21 .expect(simplifyDeviceName('iPhone 12 Pro')).eql('iPhone 12 Pro')22 .expect(simplifyDeviceName('iPhone 12 Pro Max')).eql('iPhone 12 Pro Max')23 .expect(simplifyDeviceName('iPhone 12 mini')).eql('iPhone 12 mini')24 .expect(simplifyDeviceName('iPhone 13')).eql('iPhone 13')25 .expect(simplifyDeviceName('iPhone 13 Pro')).eql('
Using AI Code Generation
1import { ClientFunction } from 'testcafe';2test('TestCafe', async t => {3 const simplifyDeviceName = ClientFunction(() => {4 return testCafeRunner.utils.simplifyDeviceName('iPhone 6');5 });6 const deviceName = await simplifyDeviceName();7 await t.expect(deviceName).eql('iphone6');8});9import { ClientFunction } from 'testcafe';10import { simplifyDeviceName } from 'testcafe-runner/utils';11test('TestCafe', async t => {12 const deviceName = simplifyDeviceName('iPhone 6');13 await t.expect(deviceName).eql('iphone6');14});15export function getBrowserAlias (browser) {16 .replace(/\s+/g, '')17 .replace(/[^a-zA-Z0-9]/g, '')18 .toLowerCase();19}20Then, you can import the method in the fixture code:21import { getBrowserAlias } from 'testcafe-browser-tools';
Using AI Code Generation
1import { ClientFunction } from 'testcafe';2const simplifyDeviceName = ClientFunction(() => {3 .getAutomations()4 .filter(a => a.constructor.name === 'Playwright')[0]5 .simplifyDeviceName('iPhone 8 Plus');6});7test('My test', async t => {8 .expect(simplifyDeviceName).eql('iphone8plus');9});
Using AI Code Generation
1import {simplifyDeviceName} from 'testcafe-browser-tools';2const deviceName = simplifyDeviceName('iPhone 6 Plus');3import {getInstallations} from 'testcafe-browser-tools';4const installations = await getInstallations();5console.log(installations);6import {getInstallations} from 'testcafe-browser-tools';7const installations = await getInstallations();8console.log(installations);9import {getInstallations} from 'testcafe-browser-tools';10const installations = await getInstallations();11console.log(installations);12import {getInstallations} from 'testcafe-browser-tools';13const installations = await getInstallations();14console.log(installations);15import {getInstallations} from 'testcafe-browser-tools';16const installations = await getInstallations();17console.log(installations);18import {getInstallations} from 'testcafe-browser-tools';19const installations = await getInstallations();20console.log(installations);21import {getInstallations} from 'testcafe-browser-tools';22const installations = await getInstallations();23console.log(installations);24import {getInstallations} from 'testcafe-browser-tools';25const installations = await getInstallations();26console.log(installations);27import {getInstallations} from 'testcafe-browser-tools';28const installations = await getInstallations();29console.log(installations);30import {getInstallations} from 'testcafe-browser-tools';
Using AI Code Generation
1import { Selector, t } from 'testcafe';2test('My Test', async t => {3 .resizeWindowToFitDevice(deviceName, {4 })5 .click('#submit-button')6 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');7});8t.resizeWindowToClientSize()9t.resizeWindowToClientSize( width, height )10import { Selector, t } from 'testcafe';11test('My Test', async t => {12 .resizeWindowToClientSize()13 .click('#submit-button')14 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');15});16t.maximizeWindow()17t.maximizeWindow()18import { Selector, t } from 'testcafe';19test('My Test', async t => {20 .maximizeWindow()21 .click('#submit-button')22 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');23});24t.takeScreenshot()25t.takeScreenshot( path [, options] )
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!!