Best JavaScript code snippet using playwright-internal
MentionDropdownMenu.js
Source: MentionDropdownMenu.js
1/*2 * Copyright (C) 2021 - present Instructure, Inc.3 *4 * This file is part of Canvas.5 *6 * Canvas is free software: you can redistribute it and/or modify it under7 * the terms of the GNU Affero General Public License as published by the Free8 * Software Foundation, version 3 of the License.9 *10 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY11 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR12 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more13 * details.14 *15 * You should have received a copy of the GNU Affero General Public License along16 * with this program. If not, see <http://www.gnu.org/licenses/>.17 */18import PropTypes from 'prop-types'19import React, {useMemo, useRef, useState} from 'react'20import MentionDropdownOption from './MentionDropdownOption'21import {View} from '@instructure/ui-view'22import {usePopper} from 'react-popper'23import {ARIA_ID_TEMPLATES} from '../../constants'24const MentionDropdownMenu = ({25 onSelect,26 onMouseEnter,27 mentionOptions,28 coordiantes,29 selectedUser,30 instanceId,31 highlightMouse,32 onOptionMouseEnter,33 isInteractive34}) => {35 // Hooks & Variables36 const directionality = tinyMCE?.activeEditor?.getParam('directionality')37 const menuRef = useRef(null)38 // Setup Popper39 const virtualReference = useMemo(() => {40 return {41 getBoundingClientRect: () => {42 return coordiantes43 }44 }45 }, [coordiantes])46 const [popperElement, setPopperElement] = useState(null)47 const {styles, attributes} = usePopper(virtualReference, popperElement, {48 placement: directionality === 'rtl' ? 'bottom-end' : 'bottom-start',49 modifiers: [50 {51 name: 'flip',52 options: {53 flipVariations: false,54 fallbackPlacements: ['bottom', 'bottom-end', 'bottom-start']55 }56 }57 ]58 })59 // Memoize map of Mention Options60 const menuItems = useMemo(() => {61 return mentionOptions.map(user => {62 return (63 <MentionDropdownOption64 {...user}65 onSelect={() => {66 onSelect({67 ...user,68 elementId: ARIA_ID_TEMPLATES.activeDescendant(instanceId, user.id)69 })70 }}71 isSelected={selectedUser === user.id}72 key={user.id}73 id={ARIA_ID_TEMPLATES.activeDescendant(instanceId, user.id)}74 highlightMouse={highlightMouse}75 onOptionMouseEnter={() => {76 onOptionMouseEnter(user)77 }}78 menuRef={menuRef}79 isInteractive={isInteractive}80 />81 )82 })83 }, [84 mentionOptions,85 selectedUser,86 instanceId,87 highlightMouse,88 isInteractive,89 onSelect,90 onOptionMouseEnter91 ])92 // Don't show if menu is empty93 if (mentionOptions?.length === 0) {94 return null95 }96 return (97 <div98 className="mention-dropdown-menu"99 ref={isInteractive ? setPopperElement : null}100 style={isInteractive ? {...styles.popper, zIndex: 10000} : null}101 onMouseEnter={isInteractive ? onMouseEnter : null}102 {...attributes.popper}103 >104 <View105 as="div"106 background="primary"107 borderWidth="small"108 borderRadius="medium"109 maxHeight="200px"110 maxWidth="400px"111 minWidth="320px"112 overflowY="auto"113 padding="none"114 shadow="above"115 width="auto"116 elementRef={el => {117 menuRef.current = el118 }}119 >120 <ul121 aria-label="Mentionable Users"122 id={ARIA_ID_TEMPLATES.ariaControlTemplate(instanceId)}123 role="listbox"124 style={{125 paddingInlineStart: '0px',126 marginBlockStart: '0px',127 marginBlockEnd: '0px',128 margin: '0'129 }}130 >131 {menuItems}132 </ul>133 </View>134 </div>135 )136}137export default MentionDropdownMenu138MentionDropdownMenu.proptypes = {139 /**140 * Array of optons to be presented to user141 */142 mentionOptions: PropTypes.array,143 /**144 * Unique ID supplied for ARIA support145 */146 instanceId: PropTypes.string,147 /**148 * cordinates for menu on screen149 */150 coordiantes: PropTypes.object,151 /**152 * Callback for selecting an item153 */154 onSelect: PropTypes.func,155 /**156 * ID of selected user157 */158 selectedUser: PropTypes.string,159 /**160 * Event for triggering onMosueOver161 */162 onMouseEnter: PropTypes.func,163 /**164 * Bool to control mouse highlighting165 */166 highlightMouse: PropTypes.bool,167 /**168 * Callback to set user on hover169 */170 onOptionMouseEnter: PropTypes.func,171 /**172 * isInteractive determines if menu will recieve events173 * This is used for the hidden menu offscreen in the RCE174 */175 isInteractive: PropTypes.bool176}177MentionDropdownMenu.defaultProps = {178 isInteractive: true,179 onSelect: () => {}...
index.js
Source: index.js
1import React, { useState } from 'react';2import PropTypes from 'prop-types';3import { Row, Col } from '../Layout';4import { SmallBody } from '../Text';5import Icon from '../Icon';67import { StyledIconButton } from './style';89const StarsRating = ({10 defaultRating,11 isInteractive,12 maxRating = 5,13 starSize = 24,14 color = '#FEC35A',15 onHoverColor = '#171F46',16 onChangeRating,17 labels18}) => {19 const [rating, setRating] = useState(defaultRating);20 const [hoveredRating, setHoveredRating] = useState(-1);21 const isHovered = idx =>22 isInteractive && hoveredRating >= idx ? onHoverColor : '';23 const handleSetRating = rating => {24 if (isInteractive) {25 setRating(rating);26 if (onChangeRating) {27 onChangeRating(rating);28 }29 }30 };31 const stars = [];32 for (let i = 0; i < maxRating; i += 1) {33 if (isHovered(i)) {34 stars.push(35 <StyledIconButton36 onClick={() => handleSetRating(i + 1)}37 onMouseEnter={() => setHoveredRating(i)}38 onMouseLeave={() => setHoveredRating(-1)}39 isInteractive={isInteractive}40 onHoverColor={isHovered(i)}41 >42 <Icon size={starSize} name='star-Filled' color={onHoverColor} />43 </StyledIconButton>44 );45 continue;46 }47 if (i + 0.5 === rating) {48 stars.push(49 <StyledIconButton50 onClick={() => handleSetRating(i + 1)}51 onMouseEnter={() => setHoveredRating(i)}52 onMouseLeave={() => setHoveredRating(-1)}53 isInteractive={isInteractive}54 onHoverColor={isHovered(i)}55 >56 <Icon size={starSize} name='Star-Half' color={color} />57 </StyledIconButton>58 );59 continue;60 }61 if (rating > i) {62 stars.push(63 rating >= i + 0.5 ? (64 <StyledIconButton65 onClick={() => handleSetRating(i + 1)}66 onMouseEnter={() => setHoveredRating(i)}67 onMouseLeave={() => setHoveredRating(-1)}68 isInteractive={isInteractive}69 onHoverColor={isHovered(i)}70 >71 <Icon size={starSize} name={'star-Filled'} color={color} />72 </StyledIconButton>73 ) : (74 <StyledIconButton75 onClick={() => handleSetRating(i + 1)}76 onMouseEnter={() => setHoveredRating(i)}77 onMouseLeave={() => setHoveredRating(-1)}78 isInteractive={isInteractive}79 onHoverColor={isHovered(i)}80 >81 <Icon size={starSize} name='star' color={color} />82 </StyledIconButton>83 )84 );85 continue;86 } else {87 stars.push(88 <StyledIconButton89 isInteractive={isInteractive}90 onClick={() => handleSetRating(i + 1)}91 onMouseEnter={() => setHoveredRating(i)}92 onMouseLeave={() => setHoveredRating(-1)}93 onHoverColor={isHovered(i)}94 >95 <Icon size={starSize} name='star' color={color} />96 </StyledIconButton>97 );98 continue;99 }100 }101102 return (103 <Col>104 <Row justify={labels && labels.length && 'space-between'} noWrap>105 {stars}106 </Row>107 {labels && (108 <Row justify='space-between'>109 {labels.map(l => (110 <SmallBody key={'stars-labels' + l}>{l}</SmallBody>111 ))}112 </Row>113 )}114 </Col>115 );116};117118StarsRating.propTypes = {119 labels: PropTypes.arrayOf(PropTypes.string),120 isInteractive: PropTypes.bool,121 onChangeRating: PropTypes.func,122 defaultRating: PropTypes.number,123 starSize: PropTypes.number,124 color: PropTypes.string,125 onHoverColor: PropTypes.string,126 maxRating: PropTypes.number127};128129StarsRating.defaultProps = {130 isInteractive: false,131 color: '#FEC35A',132 onHoverColor: '#171F46',133 starSize: 24,134 maxRating: 5,135 defaultRating: 0136};
...
browsersHelper.js
Source: browsersHelper.js
1/**2 * Copyright (c) 2015-present, Facebook, Inc.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 */7'use strict';8const browserslist = require('browserslist');9const chalk = require('chalk');10const os = require('os');11const prompts = require('prompts');12const pkgUp = require('pkg-up');13const fs = require('fs');14const defaultBrowsers = {15 production: ['>0.2%', 'not dead', 'not op_mini all'],16 development: [17 'last 1 chrome version',18 'last 1 firefox version',19 'last 1 safari version',20 ],21};22function shouldSetBrowsers(isInteractive) {23 if (!isInteractive) {24 return Promise.resolve(true);25 }26 const question = {27 type: 'confirm',28 name: 'shouldSetBrowsers',29 message:30 chalk.yellow("We're unable to detect target browsers.") +31 `\n\nWould you like to add the defaults to your ${chalk.bold(32 'package.json'33 )}?`,34 initial: true,35 };36 return prompts(question).then(answer => answer.shouldSetBrowsers);37}38function checkBrowsers(dir, isInteractive, retry = true) {39 const current = browserslist.loadConfig({ path: dir });40 if (current != null) {41 return Promise.resolve(current);42 }43 if (!retry) {44 return Promise.reject(45 new Error(46 chalk.red(47 'As of react-scripts >=2 you must specify targeted browsers.'48 ) +49 os.EOL +50 `Please add a ${chalk.underline(51 'browserslist'52 )} key to your ${chalk.bold('package.json')}.`53 )54 );55 }56 return shouldSetBrowsers(isInteractive).then(shouldSetBrowsers => {57 if (!shouldSetBrowsers) {58 return checkBrowsers(dir, isInteractive, false);59 }60 return (61 pkgUp({ cwd: dir })62 .then(filePath => {63 if (filePath == null) {64 return Promise.reject();65 }66 const pkg = JSON.parse(fs.readFileSync(filePath));67 pkg['browserslist'] = defaultBrowsers;68 fs.writeFileSync(filePath, JSON.stringify(pkg, null, 2) + os.EOL);69 browserslist.clearCaches();70 console.log();71 console.log(72 `${chalk.green('Set target browsers:')} ${chalk.cyan(73 defaultBrowsers.join(', ')74 )}`75 );76 console.log();77 })78 // Swallow any error79 .catch(() => {})80 .then(() => checkBrowsers(dir, isInteractive, false))81 );82 });83}...
isInteractive.test.js
Source: isInteractive.test.js
1// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.2let oldIsTTY;3let oldTERM;4beforeEach(() => {5 oldIsTTY = process.stdout.isTTY;6 oldTERM = process.env.TERM;7});8afterEach(() => {9 process.stdout.isTTY = oldIsTTY;10 process.env.TERM = oldTERM;11 jest.resetModules();12});13it('Returns true when running on interactive environment', () => {14 jest.doMock('is-ci', () => false);15 process.stdout.isTTY = true;16 process.env.TERM = 'xterm-256color';17 const isInteractive = require('../isInteractive').default;18 expect(isInteractive).toBe(true);19});20it('Returns false when running on a non-interactive environment', () => {21 let isInteractive;22 const expectedResult = false;23 // Test with is-ci being true and isTTY false24 jest.doMock('is-ci', () => true);25 process.stdout.isTTY = false;26 process.env.TERM = 'xterm-256color';27 isInteractive = require('../isInteractive').default;28 expect(isInteractive).toBe(expectedResult);29 // Test with is-ci being false and isTTY false30 jest.resetModules();31 jest.doMock('is-ci', () => false);32 process.stdout.isTTY = false;33 process.env.TERM = 'xterm-256color';34 isInteractive = require('../isInteractive').default;35 expect(isInteractive).toBe(expectedResult);36 // Test with is-ci being true and isTTY true37 jest.resetModules();38 jest.doMock('is-ci', () => true);39 process.stdout.isTTY = true;40 process.env.TERM = 'xterm-256color';41 isInteractive = require('../isInteractive').default;42 expect(isInteractive).toBe(expectedResult);43 // Test with dumb terminal44 jest.resetModules();45 jest.doMock('is-ci', () => false);46 process.stdout.isTTY = false;47 process.env.TERM = 'dumb';48 isInteractive = require('../isInteractive').default;49 expect(isInteractive).toBe(expectedResult);...
37isInteractive.test.js
Source: 37isInteractive.test.js
1// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.2let oldIsTTY;3let oldTERM;4beforeEach(() => {5 oldIsTTY = process.stdout.isTTY;6 oldTERM = process.env.TERM;7});8afterEach(() => {9 process.stdout.isTTY = oldIsTTY;10 process.env.TERM = oldTERM;11 jest.resetModules();12});13it('Returns true when running on interactive environment', () => {14 jest.doMock('is-ci', () => false);15 process.stdout.isTTY = true;16 process.env.TERM = 'xterm-256color';17 const isInteractive = require('../isInteractive').default;18 expect(isInteractive).toBe(true);19});20it('Returns false when running on a non-interactive environment', () => {21 let isInteractive;22 const expectedResult = false;23 // Test with is-ci being true and isTTY false24 jest.doMock('is-ci', () => true);25 process.stdout.isTTY = false;26 process.env.TERM = 'xterm-256color';27 isInteractive = require('../isInteractive').default;28 expect(isInteractive).toBe(expectedResult);29 // Test with is-ci being false and isTTY false30 jest.resetModules();31 jest.doMock('is-ci', () => false);32 process.stdout.isTTY = false;33 process.env.TERM = 'xterm-256color';34 isInteractive = require('../isInteractive').default;35 expect(isInteractive).toBe(expectedResult);36 // Test with is-ci being true and isTTY true37 jest.resetModules();38 jest.doMock('is-ci', () => true);39 process.stdout.isTTY = true;40 process.env.TERM = 'xterm-256color';41 isInteractive = require('../isInteractive').default;42 expect(isInteractive).toBe(expectedResult);43 // Test with dumb terminal44 jest.resetModules();45 jest.doMock('is-ci', () => false);46 process.stdout.isTTY = false;47 process.env.TERM = 'dumb';48 isInteractive = require('../isInteractive').default;49 expect(isInteractive).toBe(expectedResult);...
is_interactive.test.js
Source: is_interactive.test.js
1let oldIsTTY;2let oldTERM;3beforeEach(() => {4 oldIsTTY = process.stdout.isTTY;5 oldTERM = process.env.TERM;6});7afterEach(() => {8 process.stdout.isTTY = oldIsTTY;9 process.env.TERM = oldTERM;10 jest.resetModules();11});12it('Returns true when running on interactive environment', () => {13 jest.doMock('is-ci', () => false);14 process.stdout.isTTY = true;15 process.env.TERM = 'xterm-256color';16 const isInteractive = require('../is_interative').default;17 expect(isInteractive).toBe(true);18});19it('Returns false when running on a non-interactive environment', () => {20 let isInteractive;21 const expectedResult = false;22 // Test with is-ci being true and isTTY false23 jest.doMock('is-ci', () => true);24 process.stdout.isTTY = false;25 process.env.TERM = 'xterm-256color';26 isInteractive = require('../is_interative').default;27 expect(isInteractive).toBe(expectedResult);28 // Test with is-ci being false and isTTY false29 jest.resetModules();30 jest.doMock('is-ci', () => false);31 process.stdout.isTTY = false;32 process.env.TERM = 'xterm-256color';33 isInteractive = require('../is_interative').default;34 expect(isInteractive).toBe(expectedResult);35 // Test with is-ci being true and isTTY true36 jest.resetModules();37 jest.doMock('is-ci', () => true);38 process.stdout.isTTY = true;39 process.env.TERM = 'xterm-256color';40 isInteractive = require('../is_interative').default;41 expect(isInteractive).toBe(expectedResult);42 // Test with dumb terminal43 jest.resetModules();44 jest.doMock('is-ci', () => false);45 process.stdout.isTTY = false;46 process.env.TERM = 'dumb';47 isInteractive = require('../is_interative').default;48 expect(isInteractive).toBe(expectedResult);...
doll.js
Source: doll.js
...10 }11 set type(type) {12 this._type = type;13 }14 get isInteractive() {15 return this._isInteractive;16 }17 set isInteractive(isInteractive) {18 this._isInteractive = isInteractive;19 }20}...
isInteractive.js
Source: isInteractive.js
1import React from 'react';2export const isInteractive = (Component) =>3 class IsInteractive extends React.Component {4 constructor (props) {5 super(props);6 this.state = {7 isInteractive: false8 };9 }10 componentDidMount () {11 this.setState({ isInteractive: true });12 }13 render () {14 return (15 <Component { ...this.props } isInteractive={ this.state.isInteractive } />16 );17 }18 }...
Using AI Code Generation
1const { isInteractive } = require('playwright/lib/server/browserType');2console.log(isInteractive);3const { isInteractive } = require('playwright/lib/server/browserType');4console.log(isInteractive);5const { isHeadless } = require('playwright/lib/server/browserType');6console.log(isHeadless);7const { isHeadless } = require('playwright/lib/server/browserType');8console.log(isHeadless);
Using AI Code Generation
1const { isInteractive } = require('playwright/lib/server/browserType');2console.log(isInteractive());3const { isInteractive } = require('playwright/lib/server/browserType');4console.log(isInteractive());5const { isInteractive } = require('playwright/lib/server/browserType');6console.log(isInteractive());7const { isInteractive } = require('playwright/lib/server/browserType');8console.log(isInteractive());9const { isInteractive } = require('playwright/lib/server/browserType');10console.log(isInteractive());11const { isInteractive } = require('playwright/lib/server/browserType');12console.log(isInteractive());13const { isInteractive } = require('playwright/lib/server/browserType');14console.log(isInteractive());15const { isInteractive } = require('playwright/lib/server/browserType');16console.log(isInteractive());17const { isInteractive } = require('playwright/lib/server/browserType');18console.log(isInteractive());19const { isInteractive } = require('playwright/lib/server/browserType');20console.log(isInteractive());21const { isInteractive } = require('playwright/lib/server/browserType');22console.log(isInteractive());23const { isInteractive } = require('playwright/lib/server/browser
Using AI Code Generation
1const { isInteractive } = require('playwright/lib/server/supplements/recorder/recorderApp');2const { isInteractive } = require('playwright/lib/server/supplements/recorder/recorderApp');3const { isInteractive } = require('playwright/lib/server/supplements/recorder/recorderApp');4const { isInteractive } = require('playwright/lib/server/supplements/recorder/recorderApp');5const { isInteractive } = require('playwright/lib/server/supplements/recorder/recorderApp');6const { isInteractive } = require('playwright/lib/server/supplements/recorder/recorderApp');7const { isInteractive } = require('playwright/lib/server/supplements/recorder/recorderApp');8const { isInteractive } = require('playwright/lib/server/supplements/recorder/recorderApp');9const { isInteractive } = require('playwright/lib/server/supplements/recorder/recorderApp');10const { isInteractive } = require('playwright/lib/server/supplements/recorder/recorderApp
Using AI Code Generation
1const { isInteractive } = require('@playwright/test/lib/utils');2const { test, expect } = require('@playwright/test');3const { chromium } = require('playwright');4test.describe('Playwright', () => {5 test.beforeEach(async ({ page }) => {6 });7 test('should be able to click through the menu', async ({ page }) => {8 await page.click('text=Docs');9 await page.click('text=API');10 await page.click('text=Playwright');11 });12 test('should be able to click through the menu', async ({ page }) => {13 await page.click('text=Docs');14 await page.click('text=API');15 await page.click('text=Playwright');16 });17});18import { test, expect } from '@playwright/test';19import { chromium } from 'playwright';20test.describe('Playwright', () => {21 test.beforeEach(async ({ page }) => {22 });23 test('should be able to click through the menu', async ({ page }) => {24 await page.click('text=Docs');25 await page.click('text=API');26 await page.click('text=Playwright');27 });28 test('should be able to click through the menu', async ({ page }) => {29 await page.click('text=Docs');30 await page.click('text=API');
Using AI Code Generation
1const { isInteractive } = require('playwright-core/lib/utils/terminalUtils');2if (isInteractive()) {3 console.log("Running in interactive mode");4} else {5 console.log("Running in headless mode");6}
Using AI Code Generation
1const page = await context.newPage();2const isInteractive = await page._delegate.isInteractive();3console.log(isInteractive);4const page = await context.newPage();5const frame = page.mainFrame();6const isInteractive = await frame._delegate.isInteractive();7console.log(isInteractive);
Using AI Code Generation
1const { isInteractive } = require('@playwright/test/lib/server/traceViewer/ui/utils');2console.log(isInteractive());3const { isInteractive } = require('@playwright/test/lib/server/traceViewer/ui/utils');4const { chromium } = require('playwright');5(async () => {6 const browser = await chromium.launch({ headless: !isInteractive() });7 const context = await browser.newContext();8 const page = await context.newPage();9 await page.screenshot({ path: 'playwright.png' });10 await browser.close();11})();12[Apache 2.0](LICENSE)
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!