Best JavaScript code snippet using playwright-internal
index.js
Source:index.js  
1#!/usr/bin/env node2'use strict';3const program = require('commander');4const spawn = require('cross-spawn');5const chalk = require('chalk');6const path = require('path');7const fs = require('fs-extra');8const log = console.log;9program10  // å®ä¹ g å½ä»¤11  .command('g')12  // å½ä»¤ g çæè¿°13  .description('Generate a component')14  // å®ä¹ -c éé¡¹ï¼æ¥åä¸ä¸ªå¿
éåæ° componentNameï¼ç»ä»¶åç§°15  .option('-c, --component-name <componentName>', 'The name of the component')16  // å®ä¹ --no-folder é项ï¼è¡¨ç¤ºå½ä½¿ç¨è¯¥é项æ¶ï¼ç»ä»¶ä¸ä¼è¢«æä»¶å¤¹å
裹17  .option('-n, --no-folder', 'Whether the component have not it is own folder')18  // å®ä¹ -p é项ï¼è¡¨ç¤ºå½ä½¿ç¨è¯¥é项æ¶ï¼ç»ä»¶ä¸ºç»§æ¿èª React.PureComponent çç±»ç»ä»¶19  .option(20    '-p, --pure-component',21    'Whether the component is a extend from PureComponent'22  )23  // å®ä¹ -s é项ï¼è¡¨ç¤ºå½ä½¿ç¨è¯¥é项æ¶ï¼ç»ä»¶ä¸ºæ ç¶æç彿°ç»ä»¶24  .option(25    '-s, --stateless',26    'Whether the component is a extend from PureComponent'27  )28  // å®ä¹æ§è¡ g å½ä»¤åè°ç¨çåè°å½æ°29  .action((cmd, opt) => {30    // å½ -c é项没æä¼ åæ°è¿æ¥æ¶ï¼æ¥éãéåº31    if (!cmd.componentName) {32      log(chalk.red('error: missing required argument `componentName`'));33      process.exit(1);34    }35    const { argv } = process;36    // å建ç»ä»¶37    createComponent(38      argv[argv.length - 1],39      !hasFilter('-n', argv),40      hasFilter('-p', argv),41      hasFilter('-s', argv)42    );43  });44program.parse(process.argv);45// å½ä»¤è¡å¯¹å¼46function hasFilter(str, arr) {47  return arr.filter(item => { return item === str }).length48}49/**50 * å建ç»ä»¶51 * @param {string} componentName ç»ä»¶åç§°52 * @param {boolean} hasFolder æ¯å¦å«ææä»¶å¤¹53 * @param {boolean} isStateless æ¯å¦æ¯æ ç¶æç»ä»¶54 * @param {boolean} isPureComponent æ¯å¦æ¯çº¯ç»ä»¶55 */56function createComponent (57  componentName,58  hasFolder,59  isStateless = false,60  isPureComponent = false61) {62  let dirPath = path.join(process.cwd());63  // ç»ä»¶å¨æä»¶å¤¹ä¸64  if (hasFolder) {65    dirPath = path.join(dirPath, componentName);66    const result = fs.ensureDirSync(dirPath);67    // ç®å½å·²åå¨68    if (!result) {69      log(chalk.red(`${dirPath} already exists`));70      process.exit(1);71    }72    const indexJs = getIndexJs(componentName);73    const less = '';74    fs.writeFileSync(path.join(dirPath, `config.js`), indexJs);75    fs.writeFileSync(path.join(dirPath, `style.less`), less);76  }77  let component;78  // æ ç¶æç»ä»¶79  if (isStateless) {80    component = getStatelessComponent(componentName, hasFolder);81  } else {82    // æç¶æç»ä»¶83    component = getClassComponent(84      componentName,85      isPureComponent ? 'React.PureComponent' : 'React.Component',86      hasFolder87    );88  }89 90  fs.writeFileSync(path.join(dirPath, `${componentName}.jsx`), component);91  log(92    chalk.green(`The ${componentName} component was successfully generated!`)93  );94  process.exit(1);95}96 97/**98 * è·åç±»ç»ä»¶å符串99 * @param {string} componentName ç»ä»¶åç§°100 * @param {string} extendFrom ç»§æ¿èªï¼'React.Component' | 'React.PureComponent'101 * @param {boolean} hasFolder ç»ä»¶æ¯å¦å¨æä»¶å¤¹ä¸ï¼å¨æä»¶å¤¹ä¸çè¯ï¼å°±ä¼èªå¨å è½½ less æä»¶ï¼102 */103function getClassComponent(componentName, extendFrom, hasFolder) {104  return `import React, {Fragment} from 'react';105  import ReactDOM from 'react-dom';106  import zhCN from 'antd/lib/locale-provider/zh_CN';107  // import commerServer from './server';108  import Navbar from 'components/navbar';109  import moment from 'moment';110  import 'moment/locale/zh-cn';111  import './style.less';112  moment.locale('zh-cn');113  114  class ${componentName} extends React.${extendFrom ? 'Component' : 'PureComponent'} {115      constructor(props) {116          super(props);117          this.state = {118              loading: false119          };120      }121  122      componentDidMount() {123          this.query()124      }125      // è·åæ°æ®126      query = async ()=>{127          this.setState({loading: true })128          // const param = {  };129          // const res = await commerServer.nnn({...param});130          this.setState({131              loading: false 132          })133      }134      render() {135          let {  } = this.state;136  137          return (138              <LocaleProvider locale={zhCN}>139                  <div className='combination_list'>140                      <Navbar>ç»åéå®</Navbar>141                      <div className='border_layer'>142                      </div>143                  </div>144              </LocaleProvider>145          );146      }147  }148  149  const pageContent = document.getElementById('J_Page');150  if (pageContent) {151      ReactDOM.render(<${componentName} />, pageContent);152  }153  `;154}155 156/**157 * è·åæ ç¶æç»ä»¶å符串158 * @param {string} componentName ç»ä»¶åç§°159 * @param {boolean} hasFolder ç»ä»¶æ¯å¦å¨æä»¶å¤¹ä¸ï¼å¨æä»¶å¤¹ä¸çè¯ï¼å°±ä¼èªå¨å è½½ less æä»¶ï¼160 */161function getStatelessComponent(componentName, hasFolder) {162  return 'çç¥...';163}164 165/**166 * è·å index.js æä»¶å
容167 * @param {string} componentName ç»ä»¶åç§°168 */169function getIndexJs(componentName) {170  return `import ${componentName} from './${componentName}';171export default ${componentName};172`;...instance-method.test.js
Source:instance-method.test.js  
1/* eslint-env jest */2import React from 'react';3import { createMounter, ensureNoWarnings } from './helper';4import createProxy from '../../src/proxy';5const createFixtures = () => ({6  modern: {7    shouldWarnOnBind: false,8    Counter1x: class Counter1x extends React.Component {9      constructor(props) {10        super(props);11        this.state = { counter: 0 };12      }13      increment() {14        this.setState({15          counter: this.state.counter + 1,16        });17      }18      render() {19        return <span>{this.state.counter}</span>;20      }21    },22    Counter10x: class Counter10x extends React.Component {23      constructor(props) {24        super(props);25        this.state = { counter: 0 };26      }27      increment() {28        this.setState({29          counter: this.state.counter + 10,30        });31      }32      render() {33        return <span>{this.state.counter}</span>;34      }35    },36    Counter100x: class Counter100x extends React.Component {37      constructor(props) {38        super(props);39        this.state = { counter: 0 };40      }41      increment() {42        this.setState({43          counter: this.state.counter + 100,44        });45      }46      render() {47        return <span>{this.state.counter}</span>;48      }49    },50    CounterWithoutIncrementMethod: class CounterWithoutIncrementMethod extends React.Component {51      constructor(props) {52        super(props);53        this.state = { counter: 0 };54      }55      render() {56        return <span>{this.state.counter}</span>;57      }58    },59    NotPureComponent: class NotPureComponent extends React.Component {60      shouldComponentUpdate() {61        return true;62      }63      render() {64        return <span>Component</span>;65      }66    },67    IsPureComponent: class IsPureComponent extends React.PureComponent {68      render() {69        return <span>PureComponent</span>;70      }71    },72  },73});74describe('instance method', () => {75  const { getWarnSpy } = ensureNoWarnings();76  const { mount } = createMounter();77  Object.keys(createFixtures()).forEach(type => {78    describe(type, () => {79      it('gets added', () => {80        const { Counter1x, CounterWithoutIncrementMethod } = createFixtures()[type];81        const proxy = createProxy(CounterWithoutIncrementMethod);82        const Proxy = proxy.get();83        const wrapper = mount(<Proxy />);84        expect(wrapper.text()).toEqual('0');85        proxy.update(Counter1x);86        wrapper.instance().increment();87        expect(wrapper.text()).toEqual('1');88      });89      it('gets replaced', () => {90        const { Counter1x, Counter10x, Counter100x } = createFixtures()[type];91        const proxy = createProxy(Counter1x);92        const Proxy = proxy.get();93        const wrapper = mount(<Proxy />);94        expect(wrapper.text()).toEqual('0');95        wrapper.instance().increment();96        expect(wrapper.text()).toEqual('1');97        proxy.update(Counter10x);98        wrapper.instance().increment();99        mount(<Proxy />);100        expect(wrapper.text()).toEqual('11');101        proxy.update(Counter100x);102        wrapper.instance().increment();103        mount(<Proxy />);104        expect(wrapper.text()).toEqual('111');105      });106      it('removes shouldComponentUpdate', () => {107        const { IsPureComponent, NotPureComponent } = createFixtures()[type];108        const proxy = createProxy(NotPureComponent);109        const Proxy = proxy.get();110        const wrapper = mount(<Proxy />);111        expect(wrapper.text()).toEqual('Component');112        expect(wrapper.instance()).toHaveProperty('shouldComponentUpdate');113        proxy.update(IsPureComponent);114        wrapper.instance().forceUpdate();115        mount(<Proxy />);116        expect(wrapper.text()).toEqual('PureComponent');117        expect(wrapper.instance()).not.toHaveProperty('shouldComponentUpdate');118      });119      it('cant handle bound methods', () => {120        const { Counter1x, Counter10x, shouldWarnOnBind } = createFixtures()[type];121        const proxy = createProxy(Counter1x);122        const Proxy = proxy.get();123        const wrapper = mount(<Proxy />);124        const instance = wrapper.instance();125        getWarnSpy().mockReset();126        const localWarnSpy = jest.spyOn(console, 'warn');127        instance.increment = instance.increment.bind(instance);128        expect(localWarnSpy).toHaveBeenCalledTimes(shouldWarnOnBind ? 1 : 0);129        expect(wrapper.text()).toEqual('0');130        instance.increment();131        expect(wrapper.text()).toEqual('1');132        proxy.update(Counter10x);133        instance.increment();134        mount(<Proxy />);135        expect(wrapper.text()).toEqual('2'); // not 11136      });137    });138  });139  it('passes methods props thought', () => {140    const injectedMethod = (a, b) => this[24 + a + b];141    injectedMethod.staticProp = 'magic';142    class App extends React.Component {143      method() {144        return 42;145      }146    }147    App.prototype.injectedMethod = injectedMethod;148    const app1 = new App();149    expect(app1.injectedMethod).toBe(injectedMethod);150    expect(app1.injectedMethod.staticProp).toBe('magic');151    expect(String(app1.injectedMethod)).toBe(String(injectedMethod));152    const Proxy = createProxy(App).get();153    const app2 = new Proxy();154    expect(app2.injectedMethod).not.toBe(injectedMethod);155    expect(app2.injectedMethod.staticProp).toBe('magic');156    expect(app2.injectedMethod.length).toBe(2);157    expect(String(app2.injectedMethod)).toBe(String(injectedMethod));158  });...RenderTest.js
Source:RenderTest.js  
...37    }38    console.groupEnd();39  }40}41function isPureComponent(WrappedComponent) {42  return !!(WrappedComponent.prototype && WrappedComponent.prototype.isPureReactComponent);43}44const RerenderTest = (WrappedComponent, { verbose }) => {45  const Parent = isPureComponent(WrappedComponent) ? PureComponent : Component;46  return class Container extends Parent {47    componentDidUpdate(prevProps, prevState) {48      deepDiff(49          { props: prevProps, state: prevState },50          { props: this.props, state: this.state },51          WrappedComponent.name, verbose52        );53    }54    render() {55      return <WrappedComponent {...this.props} />;56    }57  };58}59export default RerenderTest;PureComponentExp.js
Source:PureComponentExp.js  
1import React, { Component, PureComponent, useState } from 'react';2class IsPureComponent extends PureComponent {3	render() {4		return (5			<div>6				<div>-----</div>7				<div>PureComponent render: {this.props.state}</div>8				<div>Render be Called: {Math.random()}</div>9			</div>10		);11	}12}13class NonComponent extends Component {14	render() {15		return (16			<div>17				<div>-----</div>18				<div>Non PureComponent render: {this.props.state}</div>19				<div>Render be Called: {Math.random()}</div>20			</div>21		);22	}23}24const Wrapper = () => {25	const [state, setState] = useState(0);26	const [value, setValue] = useState(0);27	return <div>28		<div>click the followig buttons will change Component1 and Component2 props</div>29		<button onClick={() => setValue(Math.random())}>click to change state but not pass props (Component will be rendered, but not pure component)</button>30		<button onClick={() => setState(Math.random())}>click to change state and pass props to two components</button>31		<div>Current passed props value = {state}</div>32		<div>Current NOT passed props value = {value}</div>33		<IsPureComponent state={state}/>34		<NonComponent state={state}/>35	</div>36}...isPureComponent.spec.js
Source:isPureComponent.spec.js  
2import React from 'react'3import isPureComponent from '../src/isPureComponent'4test('Simple function - pure', function () {5  const Comp = function (props) { return <div /> }6  expect(isPureComponent(Comp)).toBeTruthy()7})8test('Arrow function - pure', function () {9  const Comp = (props) => { return <div /> }10  expect(isPureComponent(Comp)).toBeTruthy()11})12test('Subclass of React.PureComponent - pure', function () {13  class Comp extends React.PureComponent {14    render () {15      return <div />16    }17  }18  expect(isPureComponent(Comp)).toBeTruthy()19})20test('Subclass of React.Component - not pure', function () {21  class Comp extends React.Component {22    render () {23      return <div />24    }25  }26  expect(isPureComponent(Comp)).toBeFalsy()27})28test('Host component - not pure', function () {29  expect(isPureComponent('div')).toBeFalsy()...PureComponent.js
Source:PureComponent.js  
1import Component from './Component';2import { shallowEqual } from './shared';3class PureComponent extends Component {4  isPureComponent = true;5  shouldComponentUpdate (nextProps, nextState) {6    return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState);7  }8}...pure-component.js
Source:pure-component.js  
1import Component from './component'2import shallowEqual from './shallow-equal'3class PureComponent extends Component {4  isPureComponent = true5  shouldComponentUpdate (nextProps, nextState) {6    return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState)7  }8}...isPureComponent.js
Source:isPureComponent.js  
1function isPureComponent (comp) {2  if (typeof comp === 'string') {3    return false4  }5  const p = comp.prototype6  return p.isPureReactComponent || !p.setState7}...Using AI Code Generation
1const { isPureComponent } = require('playwright/lib/server/frames');2const { Page } = require('playwright/lib/server/page');3const { Frame } = require('playwright/lib/server/frame');4const { ElementHandle } = require('playwright/lib/server/dom');5const { isPureComponent } = require('playwright/lib/server/frames');6const { Page } = require('playwright/lib/server/page');7const { Frame } = require('playwright/lib/server/frame');8const { ElementHandle } = require('playwright/lib/server/dom');9const { isPureComponent } = require('playwright/lib/server/frames');10const { Page } = require('playwright/lib/server/page');11const { Frame } = require('playwright/lib/server/frame');12const { ElementHandle } = require('playwright/lib/server/dom');13const { isPureComponent } = require('playwright/lib/server/frames');14const { Page } = require('playwright/lib/server/page');15const { Frame } = require('playwright/lib/server/frame');16const { ElementHandle } = require('playwright/lib/server/dom');17const { isPureComponent } = require('playwright/lib/server/frames');18const { Page } = require('playwright/lib/server/page');19const { Frame } = require('playwright/lib/server/frame');20const { ElementHandle } = require('playwright/lib/server/dom');21const { isPureComponent } = require('playwright/lib/server/frames');22const { Page } = require('playwright/lib/server/page');23const { Frame } = require('playwright/lib/server/frame');24const { ElementHandle } = require('playwright/lib/server/dom');25const { isPureComponent } = require('playwright/lib/server/frames');26const { Page } = require('playwright/lib/server/page');27const { Frame } = require('playwright/lib/server/frame');28const { ElementHandle } = require('playwright/lib/server/dom');29const { isPureComponent } =Using AI Code Generation
1const { isPureComponent } = require('playwright/lib/server/supplements/recorder/recorderSupplement');2const { Page } = require('playwright');3const { chromium } = require('playwright');4(async () => {5  const browser = await chromium.launch();6  const context = await browser.newContext();7  const page = await context.newPage();8  const pure = await isPureComponent(page, 'div');9  console.log(pure);10  await browser.close();11})();Using AI Code Generation
1const { isPureComponent } = require('@playwright/test/lib/utils');2const { Page } = require('@playwright/test/lib/page');3const { expect } = require('@playwright/test');4describe('test', () => {5  it('test', async () => {6    const page = new Page();7    const isPureComponentResult = isPureComponent(page);8    expect(isPureComponentResult).toBe(false);9  });10});Using AI Code Generation
1const { isPureComponent } = require('playwright/lib/server/frames');2const { parseSelector } = require('playwright/lib/server/common/selectors');3const { parseSelectorV2 } = require('playwright/lib/server/common/selectors2');4const selector = parseSelector('text=foo', 'css');5const selectorV2 = parseSelectorV2('text=foo', 'css');6console.log(isPureComponent(selector));7console.log(isPureComponent(selectorV2));8const selectorEngine = await page.selectorEngine();9console.log(selectorEngine.isPureComponent(selector));10const selectorEngine = await page.selectorEngine();11console.log(selectorEngine.isPureComponent(selector));Using AI Code Generation
1const { isPureComponent } = require('playwright/lib/server/domPatchers/PureComponent');2const { parseScript } = require('playwright/lib/server/common/utils');3const { parse } = require('playwright/lib/server/common/inspectorUtils');4const { parseExpression } = require('playwright/lib/server/common/utils');5const code = "const MyComponent = (props) => { return <div>{props.name}</div> }";6const script = parseScript(code);7const node = script.body[0].declarations[0].init;8const isPure = isPureComponent(node);9console.log(isPure);10{11  "dependencies": {12  }13}14[Apache 2.0](LICENSE)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!!
