playwright#Browser TypeScript Examples

The following examples show how to use playwright#Browser. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: playwrightCtx.ts    From mockiavelli with MIT License 6 votes vote down vote up
export function setupPlaywrightCtx(): PlaywrightTestCtx {
    let browser: Browser;
    let context: BrowserContext;

    const testCtx: PlaywrightTestCtx = {};

    beforeAll(async () => {
        browser = await chromium.launch({
            headless: true,
            devtools: false,
            args: ['--no-sandbox'],
        });
        context = await browser.newContext();
    });

    afterAll(async () => {
        await browser.close();
    });

    beforeEach(async () => {
        // Setup new page (tab)
        testCtx.page = await context.newPage();
        await testCtx.page.goto(`http://localhost:${PORT}`);
        testCtx.mockiavelli = await Mockiavelli.setup(testCtx.page);
        testCtx.makeRequest = makeRequestFactory(testCtx.page);
    });

    afterEach(async () => {
        await testCtx.page.close();
    });

    return testCtx;
}
Example #2
Source File: without-metamask.test.ts    From useDApp with MIT License 6 votes vote down vote up
describe(`Browser: ${browserType.name()} without Metamask`, () => {
  let page: Page
  let browser: Browser
  let context: BrowserContext

  const resetBrowserContext = async () => {
    if (page) await page.close()
    if (context) await context.close()
    if (browser) await browser.close()

    browser = await browserType.launch({ headless, slowMo })
    context = await browser.newContext()
    page = await context.newPage()
    addPageDiagnostics(page)
  }

  before(resetBrowserContext)
  after(() => browser?.close())

  describe('Balance', () => {
    it('Reads the ETH2 staking contract', async () => {
      await page.goto(`${baseUrl}balance`)

      await waitForExpect(async () => {
        expect(await page.isVisible(XPath.text('span', 'ETH2 staking contract holds:'))).to.be.true
      })
    })
  })
})
Example #3
Source File: close-browser.ts    From playwright-fluent with MIT License 6 votes vote down vote up
export async function closeBrowser(
  browser: Browser | undefined,
  options: CloseOptions,
): Promise<void> {
  if (browser === undefined) {
    return;
  }

  const contexts = browser.contexts();
  if (Array.isArray(contexts) && contexts.length > 0) {
    for (let index = 0; index < contexts.length; index++) {
      const context = contexts[index];
      try {
        await Promise.race([context.close(), sleep(options.timeoutInMilliseconds)]);
      } catch (error) {
        // eslint-disable-next-line no-console
        console.warn('Error while closing the browser context', error);
      }
    }
  }

  try {
    await Promise.race([browser.close(), sleep(options.timeoutInMilliseconds)]);
  } catch (error) {
    // eslint-disable-next-line no-console
    console.warn('Error while closing the browser', error);
  }
}
Example #4
Source File: browser.ts    From analytics-next with MIT License 6 votes vote down vote up
export async function browser(): Promise<Browser> {
  if (!br) {
    br = await playwright.chromium.launch({
      devtools: true,
      headless: !debug,
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-dev-shm-usage',
        '--disable-accelerated-2d-canvas',
        '--no-zygote',
        '--disable-gpu',
      ],
    })
  }

  return br
}
Example #5
Source File: server.ts    From Assistive-Webdriver with MIT License 5 votes vote down vote up
browsers: { [key: string]: BrowserType<Browser> } = {
  chromium,
  webkit,
  firefox
}
Example #6
Source File: a11y.spec.ts    From axe-playwright with MIT License 5 votes vote down vote up
browser: Browser
Example #7
Source File: launch-browser.ts    From playwright-fluent with MIT License 5 votes vote down vote up
export async function launchBrowser(name: BrowserName, options: LaunchOptions): Promise<Browser> {
  switch (name) {
    case 'chrome': {
      if (options && options.executablePath !== undefined) {
        const browser = await chromium.launch(options);
        return browser;
      }
      {
        const chromeOptions: LaunchOptions = {
          ...options,
          executablePath: getChromePath(),
        };
        const browser = await chromium.launch(chromeOptions);
        return browser;
      }
    }

    case 'chrome-canary': {
      if (options && options.executablePath !== undefined) {
        const browser = await chromium.launch(options);
        return browser;
      }
      {
        const chromeOptions: LaunchOptions = {
          ...options,
          executablePath: getChromeCanaryPath(),
        };
        const browser = await chromium.launch(chromeOptions);
        return browser;
      }
    }

    case 'msedge': {
      if (options && options.executablePath !== undefined) {
        const browser = await chromium.launch(options);
        return browser;
      }
      {
        const chromeOptions: LaunchOptions = {
          ...options,
          executablePath: getEdgePath(),
        };
        const browser = await chromium.launch(chromeOptions);
        return browser;
      }
    }

    case 'chromium': {
      const browser = await chromium.launch(options);
      return browser;
    }

    case 'firefox': {
      const browser = await firefox.launch(options);
      return browser;
    }

    case 'webkit': {
      const browser = await webkit.launch(options);
      return browser;
    }

    default:
      throw new Error(
        `Browser named '${name}' is unknown. It should be one of 'chrome', 'chromium', 'chrome-canary', 'firefox', 'webkit'`,
      );
  }
}
Example #8
Source File: common.ts    From jitsu with MIT License 5 votes vote down vote up
/**
 * Opens an url with given browser:
 * - throws an exception (fails the test) if result is not successful
 * - takes a screenshot and saves it to `artifacts`
 * @param browser
 * @param url
 */
export async function runUrl(
  browser: Browser,
  url: string
): Promise<PageResult> {
  let allRequests: Request[] = [];
  let consoleErrors: string[] = [];
  const page = await browser.newPage();
  page.on("request", (request) => {
    console.log("Page requested " + request.url());
    allRequests.push(request);
  });
  page.on("console", (msg: ConsoleMessage) => {
    if (msg.type() === "error") {
      consoleErrors.push(msg.text());
    }
    console.log(`Browser console message: [${msg.type()}] ${msg.text()}`);
  });
  page.on("pageerror", (err) => {
    consoleErrors.push(err.message);
    console.log(`Browser console error: ${err.message}`);
  });
  let artifactsDir = __dirname + "/../artifacts/";
  let screenshotPath =
    artifactsDir +
    url.replace("http://", "").replace("https://", "").split("/").join("_") +
    ".png";
  let result = await page.goto(url);
  console.log(`Saving screenshot of ${url} to ${screenshotPath}`);
  await page.screenshot({ path: screenshotPath });

  expect(result?.ok()).toBeTruthy();

  console.log("Waiting");
  await sleep(4000);

  await page.close();
  return { allRequests, consoleErrors, pageResponse: result as Response };
}
Example #9
Source File: core.test.ts    From clarity with MIT License 5 votes vote down vote up
browser: Browser
Example #10
Source File: PlaywrightLauncher.ts    From web with MIT License 5 votes vote down vote up
async createNewPage(browser: Browser, context: BrowserContext) {
    const playwrightPage = await this.createPageFn({ config: this.config!, browser, context });
    return new PlaywrightLauncherPage(this.config!, this.product, this.testFiles!, playwrightPage);
  }
Example #11
Source File: browser.ts    From analytics-next with MIT License 5 votes vote down vote up
br: Browser
Example #12
Source File: browser.test.ts    From blake3 with MIT License 4 votes vote down vote up
// Much of the browser code is also used in Node's wasm. We test things more
// thoroughly there because tests are easier to write and debug, these tests
// are primarily for sanity and checking browser-specific behavior.
describe('browser', () => {
  const addInputs = `window.inputs = ${JSON.stringify(inputs)}`;

  describe('webpack', () => {
    const testDir = resolve(tmpdir(), 'blake3-browser-test');
    let server: Server;
    let browser: Browser;
    let page: Page;

    /**
     * Builds the browser lib into the testDir.
     */
    async function buildWebpack() {
      try {
        mkdirSync(testDir);
      } catch {
        // already exists, probably
      }

      writeFileSync(
        resolve(testDir, 'entry-src.js'),
        `import("blake3/browser").then(b3 => window.blake3 = b3);`,
      );

      const stats = await new Promise<webpack.Stats>((res, rej) =>
        webpack(
          {
            mode: 'production',
            devtool: 'source-map',
            entry: resolve(testDir, 'entry-src.js'),
            output: {
              path: testDir,
              filename: 'main.js',
            },
            resolve: {
              alias: {
                'blake3/browser': resolve(__dirname, '../', 'browser.js'),
              },
            },
          },
          (err, stats) => (err ? rej(err) : res(stats)),
        ),
      );

      if (stats.hasErrors()) {
        throw stats.toString('errors-only');
      }

      writeFileSync(resolve(testDir, 'index.html'), `<script src="/main.js"></script>`);
    }

    async function serve() {
      server = createServer((req, res) => handler(req, res, { public: testDir }));
      await new Promise<void>(resolve => server.listen(0, resolve));
    }

    before(async function() {
      await buildWebpack();
      await serve();

      this.timeout(20 * 1000);

      const { port } = server.address() as AddressInfo;
      browser = await chromium.launch();
      page = await browser.newPage();
      await page.goto(`http://localhost:${port}`);
      await page.waitForFunction('!!window.blake3');
      await page.evaluate(addInputs);
    });

    runTests({
      get page() {
        return page;
      },
    });

    after(async () => {
      await browser?.close();
      server?.close();
    });
  });

  describe('native browser', () => {
    let server: Server;
    let page: Page;
    let browser: Browser;

    async function serve() {
      server = createServer((req, res) => handler(req, res, { public: resolve(__dirname, '..') }));
      await new Promise<void>(resolve => server.listen(0, resolve));
    }

    before(async function() {
      await serve();

      this.timeout(20 * 1000);

      const { port } = server.address() as AddressInfo;
      browser = await chromium.launch();
      page = await browser.newPage();
      page.on('console', console.log);
      page.on('pageerror', console.log);
      page.on('pageerror', console.log);
      await page.goto(`http://localhost:${port}/browser-async.test.html`);
      await page.waitForFunction('!!window.blake3');
      await page.evaluate(addInputs);
    });

    runTests({
      get page() {
        return page;
      },
    });

    after(async () => {
      await browser?.close();
      server.close();
    });
  });
});
Example #13
Source File: are-options-already-selected-in-handle.chromium.test.ts    From playwright-fluent with MIT License 4 votes vote down vote up
describe('are options already selected in handle', (): void => {
  let browser: Browser | undefined = undefined;

  // eslint-disable-next-line @typescript-eslint/no-empty-function
  beforeEach((): void => {});

  afterEach(async (): Promise<void> => {
    if (browser) {
      await browser.close();
    }
  });

  test('should throw when selector is not a select - chromium', async (): Promise<void> => {
    // Given
    browser = await chromium.launch({ headless: true });
    const browserContext = await browser.newContext({ viewport: null });
    const page = await browserContext.newPage();
    const url = `file:${path.join(__dirname, 'are-options-already-selected-in-handle.test.html')}`;
    await page.goto(url);

    const selector = '#empty-input';
    const handle = await page.$(selector);

    // When
    // Then
    const expectedError = new Error("Cannot find any options in selector '#empty-input'");

    await SUT.areOptionsAlreadySelectedInHandle(handle, selector, ['foobar']).catch((error): void =>
      expect(error).toMatchObject(expectedError),
    );
  });

  test('should check that all options are already selected in a disabled select - chromium', async (): Promise<void> => {
    // Given
    browser = await chromium.launch({ headless: true });
    const browserContext = await browser.newContext({ viewport: null });
    const page = await browserContext.newPage();
    const url = `file:${path.join(__dirname, 'are-options-already-selected-in-handle.test.html')}`;
    await page.goto(url);

    // When
    const selector = '#disabled-select';
    const expectedOptionLabels = ['label 2', 'label 3'];
    const handle = await page.$(selector);
    const result = await SUT.areOptionsAlreadySelectedInHandle(
      handle,
      selector,
      expectedOptionLabels,
    );

    // Then
    expect(result).toBe(true);
  });

  test('should check that all options are not already selected in a disabled select - chromium', async (): Promise<void> => {
    // Given
    browser = await chromium.launch({ headless: true });
    const browserContext = await browser.newContext({ viewport: null });
    const page = await browserContext.newPage();
    const url = `file:${path.join(__dirname, 'are-options-already-selected-in-handle.test.html')}`;
    await page.goto(url);

    // When
    const selector = '#disabled-select';
    const expectedOptionLabels = ['label 1', 'label 2', 'label 3'];
    const handle = await page.$(selector);
    const result = await SUT.areOptionsAlreadySelectedInHandle(
      handle,
      selector,
      expectedOptionLabels,
    );

    // Then
    expect(result).toBe(false);
  });

  test('should return false when select has no options - chromium', async (): Promise<void> => {
    // Given
    browser = await chromium.launch({ headless: true });
    const browserContext = await browser.newContext({ viewport: null });
    const page = await browserContext.newPage();
    const url = `file:${path.join(__dirname, 'are-options-already-selected-in-handle.test.html')}`;
    await page.goto(url);

    // When
    const selector = '#no-options-select';
    const expectedOptionLabels = ['label 1', 'label 2', 'label 3'];
    const handle = await page.$(selector);
    const result = await SUT.areOptionsAlreadySelectedInHandle(
      handle,
      selector,
      expectedOptionLabels,
    );

    // Then
    expect(result).toBe(false);
  });
});