Best JavaScript code snippet using playwright-internal
getExports.js
Source:getExports.js  
1import { expect } from  'chai';2import semver from 'semver';3import sinon from 'sinon';4import eslintPkg from 'eslint/package.json';5import * as tsConfigLoader from 'tsconfig-paths/lib/tsconfig-loader';6import ExportMap from '../../../src/ExportMap';7import * as fs from 'fs';8import { getFilename } from '../utils';9import * as unambiguous from 'eslint-module-utils/unambiguous';10describe('ExportMap', function () {11  const fakeContext = {12    getFilename: getFilename,13    settings: {},14    parserPath: 'babel-eslint',15  };16  it('handles ExportAllDeclaration', function () {17    let imports;18    expect(function () {19      imports = ExportMap.get('./export-all', fakeContext);20    }).not.to.throw(Error);21    expect(imports).to.exist;22    expect(imports.has('foo')).to.be.true;23  });24  it('returns a cached copy on subsequent requests', function () {25    expect(ExportMap.get('./named-exports', fakeContext))26      .to.exist.and.equal(ExportMap.get('./named-exports', fakeContext));27  });28  it('does not return a cached copy after modification', (done) => {29    const firstAccess = ExportMap.get('./mutator', fakeContext);30    expect(firstAccess).to.exist;31    // mutate (update modified time)32    const newDate = new Date();33    fs.utimes(getFilename('mutator.js'), newDate, newDate, (error) => {34      expect(error).not.to.exist;35      expect(ExportMap.get('./mutator', fakeContext)).not.to.equal(firstAccess);36      done();37    });38  });39  it('does not return a cached copy with different settings', () => {40    const firstAccess = ExportMap.get('./named-exports', fakeContext);41    expect(firstAccess).to.exist;42    const differentSettings = Object.assign(43      {},44      fakeContext,45      { parserPath: 'espree' },46    );47    expect(ExportMap.get('./named-exports', differentSettings))48      .to.exist.and49      .not.to.equal(firstAccess);50  });51  it('does not throw for a missing file', function () {52    let imports;53    expect(function () {54      imports = ExportMap.get('./does-not-exist', fakeContext);55    }).not.to.throw(Error);56    expect(imports).not.to.exist;57  });58  it('exports explicit names for a missing file in exports', function () {59    let imports;60    expect(function () {61      imports = ExportMap.get('./exports-missing', fakeContext);62    }).not.to.throw(Error);63    expect(imports).to.exist;64    expect(imports.has('bar')).to.be.true;65  });66  it('finds exports for an ES7 module with babel-eslint', function () {67    const path = getFilename('jsx/FooES7.js');68    const contents = fs.readFileSync(path, { encoding: 'utf8' });69    const imports = ExportMap.parse(70      path,71      contents,72      { parserPath: 'babel-eslint', settings: {} },73    );74    expect(imports, 'imports').to.exist;75    expect(imports.errors).to.be.empty;76    expect(imports.get('default'), 'default export').to.exist;77    expect(imports.has('Bar')).to.be.true;78  });79  context('deprecation metadata', function () {80    function jsdocTests(parseContext, lineEnding) {81      context('deprecated imports', function () {82        let imports;83        before('parse file', function () {84          const path = getFilename('deprecated.js');85          const contents = fs.readFileSync(path, { encoding: 'utf8' }).replace(/[\r]\n/g, lineEnding);86          imports = ExportMap.parse(path, contents, parseContext);87          // sanity checks88          expect(imports.errors).to.be.empty;89        });90        it('works with named imports.', function () {91          expect(imports.has('fn')).to.be.true;92          expect(imports.get('fn'))93            .to.have.nested.property('doc.tags[0].title', 'deprecated');94          expect(imports.get('fn'))95            .to.have.nested.property('doc.tags[0].description', 'please use \'x\' instead.');96        });97        it('works with default imports.', function () {98          expect(imports.has('default')).to.be.true;99          const importMeta = imports.get('default');100          expect(importMeta).to.have.nested.property('doc.tags[0].title', 'deprecated');101          expect(importMeta).to.have.nested.property('doc.tags[0].description', 'this is awful, use NotAsBadClass.');102        });103        it('works with variables.', function () {104          expect(imports.has('MY_TERRIBLE_ACTION')).to.be.true;105          const importMeta = imports.get('MY_TERRIBLE_ACTION');106          expect(importMeta).to.have.nested.property(107            'doc.tags[0].title', 'deprecated');108          expect(importMeta).to.have.nested.property(109            'doc.tags[0].description', 'please stop sending/handling this action type.');110        });111        context('multi-line variables', function () {112          it('works for the first one', function () {113            expect(imports.has('CHAIN_A')).to.be.true;114            const importMeta = imports.get('CHAIN_A');115            expect(importMeta).to.have.nested.property(116              'doc.tags[0].title', 'deprecated');117            expect(importMeta).to.have.nested.property(118              'doc.tags[0].description', 'this chain is awful');119          });120          it('works for the second one', function () {121            expect(imports.has('CHAIN_B')).to.be.true;122            const importMeta = imports.get('CHAIN_B');123            expect(importMeta).to.have.nested.property(124              'doc.tags[0].title', 'deprecated');125            expect(importMeta).to.have.nested.property(126              'doc.tags[0].description', 'so awful');127          });128          it('works for the third one, etc.', function () {129            expect(imports.has('CHAIN_C')).to.be.true;130            const importMeta = imports.get('CHAIN_C');131            expect(importMeta).to.have.nested.property(132              'doc.tags[0].title', 'deprecated');133            expect(importMeta).to.have.nested.property(134              'doc.tags[0].description', 'still terrible');135          });136        });137      });138      context('full module', function () {139        let imports;140        before('parse file', function () {141          const path = getFilename('deprecated-file.js');142          const contents = fs.readFileSync(path, { encoding: 'utf8' });143          imports = ExportMap.parse(path, contents, parseContext);144          // sanity checks145          expect(imports.errors).to.be.empty;146        });147        it('has JSDoc metadata', function () {148          expect(imports.doc).to.exist;149        });150      });151    }152    context('default parser', function () {153      jsdocTests({154        parserPath: 'espree',155        parserOptions: {156          ecmaVersion: 2015,157          sourceType: 'module',158          attachComment: true,159        },160        settings: {},161      }, '\n');162      jsdocTests({163        parserPath: 'espree',164        parserOptions: {165          ecmaVersion: 2015,166          sourceType: 'module',167          attachComment: true,168        },169        settings: {},170      }, '\r\n');171    });172    context('babel-eslint', function () {173      jsdocTests({174        parserPath: 'babel-eslint',175        parserOptions: {176          ecmaVersion: 2015,177          sourceType: 'module',178          attachComment: true,179        },180        settings: {},181      }, '\n');182      jsdocTests({183        parserPath: 'babel-eslint',184        parserOptions: {185          ecmaVersion: 2015,186          sourceType: 'module',187          attachComment: true,188        },189        settings: {},190      }, '\r\n');191    });192  });193  context('exported static namespaces', function () {194    const espreeContext = { parserPath: 'espree', parserOptions: { ecmaVersion: 2015, sourceType: 'module' }, settings: {} };195    const babelContext = { parserPath: 'babel-eslint', parserOptions: { ecmaVersion: 2015, sourceType: 'module' }, settings: {} };196    it('works with espree & traditional namespace exports', function () {197      const path = getFilename('deep/a.js');198      const contents = fs.readFileSync(path, { encoding: 'utf8' });199      const a = ExportMap.parse(path, contents, espreeContext);200      expect(a.errors).to.be.empty;201      expect(a.get('b').namespace).to.exist;202      expect(a.get('b').namespace.has('c')).to.be.true;203    });204    it('captures namespace exported as default', function () {205      const path = getFilename('deep/default.js');206      const contents = fs.readFileSync(path, { encoding: 'utf8' });207      const def = ExportMap.parse(path, contents, espreeContext);208      expect(def.errors).to.be.empty;209      expect(def.get('default').namespace).to.exist;210      expect(def.get('default').namespace.has('c')).to.be.true;211    });212    it('works with babel-eslint & ES7 namespace exports', function () {213      const path = getFilename('deep-es7/a.js');214      const contents = fs.readFileSync(path, { encoding: 'utf8' });215      const a = ExportMap.parse(path, contents, babelContext);216      expect(a.errors).to.be.empty;217      expect(a.get('b').namespace).to.exist;218      expect(a.get('b').namespace.has('c')).to.be.true;219    });220  });221  context('deep namespace caching', function () {222    const espreeContext = { parserPath: 'espree', parserOptions: { ecmaVersion: 2015, sourceType: 'module' }, settings: {} };223    let a;224    before('sanity check and prime cache', function (done) {225      // first version226      fs.writeFileSync(getFilename('deep/cache-2.js'),227        fs.readFileSync(getFilename('deep/cache-2a.js')));228      const path = getFilename('deep/cache-1.js');229      const contents = fs.readFileSync(path, { encoding: 'utf8' });230      a = ExportMap.parse(path, contents, espreeContext);231      expect(a.errors).to.be.empty;232      expect(a.get('b').namespace).to.exist;233      expect(a.get('b').namespace.has('c')).to.be.true;234      // wait ~1s, cache check is 1s resolution235      setTimeout(function reup() {236        fs.unlinkSync(getFilename('deep/cache-2.js'));237        // swap in a new file and touch it238        fs.writeFileSync(getFilename('deep/cache-2.js'),239          fs.readFileSync(getFilename('deep/cache-2b.js')));240        done();241      }, 1100);242    });243    it('works', function () {244      expect(a.get('b').namespace.has('c')).to.be.false;245    });246    after('remove test file', (done) => fs.unlink(getFilename('deep/cache-2.js'), done));247  });248  context('Map API', function () {249    context('#size', function () {250      it('counts the names', () => expect(ExportMap.get('./named-exports', fakeContext))251        .to.have.property('size', 12));252      it('includes exported namespace size', () => expect(ExportMap.get('./export-all', fakeContext))253        .to.have.property('size', 1));254    });255  });256  context('issue #210: self-reference', function () {257    it(`doesn't crash`, function () {258      expect(() => ExportMap.get('./narcissist', fakeContext)).not.to.throw(Error);259    });260    it(`'has' circular reference`, function () {261      expect(ExportMap.get('./narcissist', fakeContext))262        .to.exist.and.satisfy(m => m.has('soGreat'));263    });264    it(`can 'get' circular reference`, function () {265      expect(ExportMap.get('./narcissist', fakeContext))266        .to.exist.and.satisfy(m => m.get('soGreat') != null);267    });268  });269  context('issue #478: never parse non-whitelist extensions', function () {270    const context = Object.assign({}, fakeContext,271      { settings: { 'import/extensions': ['.js'] } });272    let imports;273    before('load imports', function () {274      imports = ExportMap.get('./typescript.ts', context);275    });276    it('returns nothing for a TypeScript file', function () {277      expect(imports).not.to.exist;278    });279  });280  context('alternate parsers', function () {281    const configs = [282      // ['string form', { 'typescript-eslint-parser': '.ts' }],283    ];284    if (semver.satisfies(eslintPkg.version, '>5')) {285      configs.push(['array form', { '@typescript-eslint/parser': ['.ts', '.tsx'] }]);286    }287    if (semver.satisfies(eslintPkg.version, '<6')) {288      configs.push(['array form', { 'typescript-eslint-parser': ['.ts', '.tsx'] }]);289    }290    configs.forEach(([description, parserConfig]) => {291      describe(description, function () {292        const context = Object.assign({}, fakeContext,293          { settings: {294            'import/extensions': ['.js'],295            'import/parsers': parserConfig,296          } });297        let imports;298        before('load imports', function () {299          this.timeout(20000);  // takes a long time :shrug:300          sinon.spy(tsConfigLoader, 'tsConfigLoader');301          imports = ExportMap.get('./typescript.ts', context);302        });303        after('clear spies', function () {304          tsConfigLoader.tsConfigLoader.restore();305        });306        it('returns something for a TypeScript file', function () {307          expect(imports).to.exist;308        });309        it('has no parse errors', function () {310          expect(imports).property('errors').to.be.empty;311        });312        it('has exported function', function () {313          expect(imports.has('getFoo')).to.be.true;314        });315        it('has exported typedef', function () {316          expect(imports.has('MyType')).to.be.true;317        });318        it('has exported enum', function () {319          expect(imports.has('MyEnum')).to.be.true;320        });321        it('has exported interface', function () {322          expect(imports.has('Foo')).to.be.true;323        });324        it('has exported abstract class', function () {325          expect(imports.has('Bar')).to.be.true;326        });327        it('should cache tsconfig until tsconfigRootDir parser option changes', function () {328          const customContext = Object.assign(329            {},330            context,331            {332              parserOptions: {333                tsconfigRootDir: null,334              },335            },336          );337          expect(tsConfigLoader.tsConfigLoader.callCount).to.equal(0);338          ExportMap.parse('./baz.ts', 'export const baz = 5', customContext);339          expect(tsConfigLoader.tsConfigLoader.callCount).to.equal(1);340          ExportMap.parse('./baz.ts', 'export const baz = 5', customContext);341          expect(tsConfigLoader.tsConfigLoader.callCount).to.equal(1);342          const differentContext = Object.assign(343            {},344            context,345            {346              parserOptions: {347                tsconfigRootDir: process.cwd(),348              },349            },350          );351          ExportMap.parse('./baz.ts', 'export const baz = 5', differentContext);352          expect(tsConfigLoader.tsConfigLoader.callCount).to.equal(2);353        });354      });355    });356  });357  // todo: move to utils358  describe('unambiguous regex', function () {359    const testFiles = [360      ['deep/b.js', true],361      ['bar.js', true],362      ['deep-es7/b.js', true],363      ['common.js', false],364    ];365    for (const [testFile, expectedRegexResult] of testFiles) {366      it(`works for ${testFile} (${expectedRegexResult})`, function () {367        const content = fs.readFileSync('./tests/files/' + testFile, 'utf8');368        expect(unambiguous.test(content)).to.equal(expectedRegexResult);369      });370    }371  });...config-loader.js
Source:config-loader.js  
...25            addMatchAll: explicitParams.addMatchAll26        };27    }28    // Load tsconfig and create path matching function29    var loadResult = tsConfigLoader({30        cwd: cwd,31        getEnv: function (key) { return process.env[key]; }32    });33    if (!loadResult.tsConfigPath) {34        return {35            resultType: "failed",36            message: "Couldn't find tsconfig.json"37        };38    }39    if (!loadResult.baseUrl) {40        return {41            resultType: "failed",42            message: "Missing baseUrl in compilerOptions",43            jsx: loadResult.jsx,...Using AI Code Generation
1const { tsConfigLoader } = require('@playwright/test');2const { chromium } = require('playwright');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.screenshot({ path: `example.png` });8  await browser.close();9})();10{11  "compilerOptions": {12  },13}14{15  "scripts": {16  },17  "dependencies": {18  },19  "devDependencies": {20  }21}Using AI Code Generation
1const { chromium } = require('playwright');2const tsConfigLoader = require('playwright/lib/server/tsConfigLoader');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.screenshot({ path: `example.png` });8  await browser.close();9})();10{11  "compilerOptions": {12  }13}14const { chromium } = require('playwright');15const tsConfigLoader = require('playwright/lib/server/tsConfigLoader');16(async () => {17  const browser = await chromium.launch();18  const context = await browser.newContext();19  const page = await context.newPage();20  await page.screenshot({ path: `example.png` });21  await browser.close();22})();23{24  "compilerOptions": {25  }26}27const { chromium } = require('playwright');Using AI Code Generation
1const { tsConfigLoader } = require('@playwright/test');2const { test, expect } = require('@playwright/test');3test('test', async ({ page }) => {4  const title = page.locator('.navbar__inner .navbar__title');5  await expect(title).toHaveText('Playwright');6});7tsConfigLoader({8  'compilerOptions': {9    'paths': {10    }11  }12});Using AI Code Generation
1const { tsConfigLoader } = require('playwright');2const { chromium } = require('playwright');3const { expect } = require('chai');4const tsConfig = tsConfigLoader('./tsconfig.json');5(async () => {6  const browser = await chromium.launch();7  const context = await browser.newContext({8  });9  const page = await context.newPage();10  console.log(await page.title());11  await browser.close();12})();13{14  "compilerOptions": {15  },16}17{18  "scripts": {19  },20  "dependencies": {21  }22}Using AI Code Generation
1const playwright = require('playwright');2const tsConfigLoader = require('playwright/lib/server/tsconfig').tsConfigLoader;3const { page, browser, context } = await tsConfigLoader('tsconfig.json', async () => {4  return await playwright.chromium.launch();5});6const playwright = require('playwright');7const tsConfigLoader = require('playwright/lib/server/tsconfig').tsConfigLoader;8const { page, browser, context } = await tsConfigLoader('tsconfig.json', async (options) => {9  return await playwright.chromium.launch(options);10});11const playwright = require('playwright');12const tsConfigLoader = require('playwright/lib/server/tsconfig').tsConfigLoader;13const { page, browser, context } = await tsConfigLoader('tsconfig.json', async (options, useWebSocket) => {14  return await playwright.chromium.launch(options, useWebSocket);15});16const playwright = require('playwright');17const tsConfigLoader = require('playwright/lib/server/tsconfig').tsConfigLoader;18const { page, browser, context } = await tsConfigLoader('tsconfig.json', async (options, useWebSocket, launchType) => {19  return await playwright.chromium.launch(options, useWebSocket, launchType);20});21const playwright = require('playwright');22const tsConfigLoader = require('playwright/lib/server/tsconfig').tsConfigLoader;23const { page, browser, context } = await tsConfigLoader('tsconfig.json', async (options, useWebSocket, launchType, executablePath) => {24  return await playwright.chromium.launch(options, useWebSocket, launchType, executablePath);25});26const playwright = require('playwright');27const tsConfigLoader = require('playwright/lib/server/tsconfig').tsConfigLoader;28const { page, browser, context } = await tsConfigLoader('tsconfig.json', async (options, useWebSocket, launchType, executablePath, slowMo) => {29  return await playwright.chromium.launch(options, useWebSocket, launchType, executablePath, slowMo);30});Using AI Code Generation
1const { tsConfigLoader } = require('playwright/lib/utils/tsconfig');2const tsConfig = tsConfigLoader.loadConfig();3const rootDir = tsConfig.options.rootDir;4const { tsConfigLoader } = require('playwright/lib/utils/tsconfig');5const tsConfig = tsConfigLoader.loadConfig();6const rootDir = tsConfig.options.rootDir;7const { tsConfigLoader } = require('playwright/lib/utils/tsconfig');8const tsConfig = tsConfigLoader.loadConfig();9const rootDir = tsConfig.options.rootDir;10const { tsConfigLoader } = require('playwright/lib/utils/tsconfig');11const tsConfig = tsConfigLoader.loadConfig();12const rootDir = tsConfig.options.rootDir;13const { tsConfigLoader } = require('playwright/lib/utils/tsconfig');14const tsConfig = tsConfigLoader.loadConfig();15const rootDir = tsConfig.options.rootDir;16const { tsConfigLoader } = require('playwright/lib/utils/tsconfig');17const tsConfig = tsConfigLoader.loadConfig();18const rootDir = tsConfig.options.rootDir;19const { tsConfigLoader } = require('playwright/lib/utils/tsconfig');20const tsConfig = tsConfigLoader.loadConfig();21const rootDir = tsConfig.options.rootDir;22const { tsConfigLoader } = require('playwright/lib/utils/tsconfig');23const tsConfig = tsConfigLoader.loadConfig();24const rootDir = tsConfig.options.rootDir;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!!
