playwright#chromium TypeScript Examples

The following examples show how to use playwright#chromium. 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: sandbox.spec.ts    From playwright-typescript-ts-jest-jest-assert with MIT License 6 votes vote down vote up
describe("Sandbox", () => {
  beforeAll(async () => {
    browser = process.env.GITHUB_ACTIONS
      ? await chromium.launch()
      : await chromium.launch({ headless: false });
    page = await browser.newPage();

    await page
      .goto("https://e2e-boilerplate.github.io/sandbox/", {
        waitUntil: "networkidle0",
      })
      // tslint:disable-next-line:no-empty
      .catch(() => {});
  });

  afterAll(() => {
    if (!page.isClosed()) {
      browser.close();
    }
  });

  test("should be on the sandbox", async () => {
    await page.waitForSelector("h1");
    const title = await page.$eval(
      "h1",
      (el: { textContent: any }) => el.textContent
    );

    assert.strictEqual(await page.title(), "Sandbox");
    assert.strictEqual(title, "Sandbox");
  });
});
Example #3
Source File: sandbox.spec.ts    From playwright-typescript-ts-jest-jest-expect with MIT License 6 votes vote down vote up
describe("Sandbox", () => {
  beforeAll(async () => {
    browser = process.env.GITHUB_ACTIONS
      ? await chromium.launch()
      : await chromium.launch({ headless: false });
    page = await browser.newPage();

    await page
      .goto("https://e2e-boilerplate.github.io/sandbox/", {
        waitUntil: "networkidle0",
      })
      // tslint:disable-next-line:no-empty
      .catch(() => {});
  });

  afterAll(() => {
    if (!page.isClosed()) {
      browser.close();
    }
  });

  test("should be on the sandbox", async () => {
    await page.waitForSelector("h1");
    const title = await page.$eval(
      "h1",
      (el: { textContent: any }) => el.textContent
    );

    expect(await page.title()).toEqual("Sandbox");
    expect(title).toEqual("Sandbox");
  });
});
Example #4
Source File: get-client-rectangle-of.chromium.test.ts    From playwright-fluent with MIT License 6 votes vote down vote up
describe('get client rectangle', (): 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 return an error when selector is not found - chromium', async (): Promise<void> => {
    // Given
    browser = await chromium.launch({ headless: true });
    const browserContext = await browser.newContext({ viewport: null });
    const page = await browserContext.newPage();

    // When

    // Then
    const expectedError = new Error(
      'page.$eval: Error: failed to find element matching selector "foobar"',
    );
    await SUT.getClientRectangleOf('foobar', page).catch((error): void =>
      expect(error).toMatchObject(expectedError),
    );
  });
});
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
describe('Playwright web page accessibility test', () => {
  each([
    [
      'on page with detectable accessibility issues',
      `file://${process.cwd()}/test/site.html`,
    ],
    [
      'on page with no detectable accessibility issues',
      `file://${process.cwd()}/test/site-no-accessibility-issues.html`,
    ],
  ]).it('check a11y %s', async (description, site) => {
    const log = jest.spyOn(global.console, 'log')

    browser = await chromium.launch({ args: ['--no-sandbox'] })
    page = await browser.newPage()
    await page.goto(site)
    await injectAxe(page)
    await checkA11y(
      page,
      'form',
      {
        axeOptions: {
          runOnly: {
            type: 'tag',
            values: ['wcag2a'],
          },
        },
      },
      true,
    )

    // condition to check console logs for both the cases
    expect(log).toHaveBeenCalledWith(
      expect.stringMatching(/(accessibility|impact)/i),
    )
  })

  afterEach(async () => {
    await browser.close()
  })
})
Example #7
Source File: vuetify-navigation.ts    From playwright-session with Apache License 2.0 5 votes vote down vote up
(async () => {
  const browser = await chromium.launch();

  // Recorder is initalizing required events collection, to later be able to replay a Playwright session in the UI.
  // Session file, that can be loaded in the UI, will be saved to ./vuetify-session-events.ldjson
  const { page } = await initializeRecorder(browser, "vuetify-session-events");

  await page.goto("https://vuetifyjs.com/en/");

  await page.evaluate(() => console.log("Adding sample console log 1"));
  await page.evaluate(() => console.warn("Adding sample console log 2"));
  await page.evaluate(() => console.info("Adding sample console log 3"));
  await page.evaluate(() => console.error("Adding sample console log 4"));
  await page.evaluate(() => console.debug("Adding sample console log 5"));

  await page.click('a[href="/en/getting-started/quick-start/"]');

  await page.click('text="UI Components"');

  await page.click('text="Form inputs & controls"');

  await page.click('text="Forms"');

  await page.waitForSelector('#usage .v-example input[type="text"]');

  const inputs = await page.$$('#usage .v-example input[type="text"]');

  await page.click("#usage h2");

  // Adding timeouts here, to show down Playwright, and make recorded session a bit smoother.
  await new Promise((r) => setTimeout(r, 1000));

  await inputs[0].fill("Welcome");
  await new Promise((r) => setTimeout(r, 500));
  await inputs[1].fill("To");
  await new Promise((r) => setTimeout(r, 500));
  await inputs[2].fill("Playwright-Session");

  await new Promise((r) => setTimeout(r, 3000));

  await browser.close();
})();
Example #8
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 #9
Source File: embedded.test.ts    From jitsu with MIT License 5 votes vote down vote up
beforeAll(async () => {
  await server.init();
  browser = await chromium.launch();
});
Example #10
Source File: helper.ts    From clarity with MIT License 5 votes vote down vote up
export async function launch(): Promise<Browser> {
    return chromium.launch({ headless: true, args: ['--no-sandbox'] });
}
Example #11
Source File: index.ts    From firetable with Apache License 2.0 4 votes vote down vote up
(async () => {
  const browser = await chromium.launch({
    headless: false,
  });
  const context = await browser.newContext();

  // Open new page
  const page = await context.newPage();

  await authenticateUser(page);

  await page.goto("http://localhost:3000/table/test");
  // Click text="Add Column"
  await page.click(
    "//div[starts-with(normalize-space(.), 'EdwardKnightEd has had a multi decade career in European banking and capital mar') and normalize-space(@role)='row']/div[2][normalize-space(@role)='gridcell']/div/div/div/div[normalize-space(@role)='button']"
  );

  // Click //li[normalize-space(.)='LON3' and normalize-space(@role)='option']/*[local-name()="svg"]
  await page.click(
    "//li[normalize-space(.)='LON3' and normalize-space(@role)='option']/*[local-name()=\"svg\"]"
  );

  // Click //div[normalize-space(.)='Beijing' and normalize-space(@role)='button']
  await page.click(
    "//div[normalize-space(.)='Beijing' and normalize-space(@role)='button']"
  );

  // Click //li[normalize-space(.)='India' and normalize-space(@role)='option']/*[local-name()="svg"]
  await page.click(
    "//li[normalize-space(.)='India' and normalize-space(@role)='option']/*[local-name()=\"svg\"]"
  );

  // Click //li[normalize-space(.)='Oslo' and normalize-space(@role)='option']
  await page.click(
    "//li[normalize-space(.)='Oslo' and normalize-space(@role)='option']"
  );

  // Click text="Add Row"
  await page.click('text="Add Row"');

  // Click //button[normalize-space(.)='Hide']
  await page.click("//button[normalize-space(.)='Hide']");

  // Click li[role="option"] >> text="Department"
  await page.click('li[role="option"] >> text="Department"');

  // Click li[role="option"] >> text="Location"
  await page.click('li[role="option"] >> text="Location"');

  // Click li[role="option"] >> text="Designation"
  await page.click('li[role="option"] >> text="Designation"');

  // Click li[role="option"] >> text="Employment Type"
  await page.click('li[role="option"] >> text="Employment Type"');

  // Click text="Done"
  await page.click('text="Done"');

  // Click .MuiGrid-root.MuiGrid-item .MuiGrid-root .MuiButtonBase-root .MuiButton-label .MuiButton-startIcon .MuiSvgIcon-root path
  await page.click(
    ".MuiGrid-root.MuiGrid-item .MuiGrid-root .MuiButtonBase-root .MuiButton-label .MuiButton-startIcon .MuiSvgIcon-root path"
  );

  // Click //div[normalize-space(.)='Select Column']
  await page.click("//div[normalize-space(.)='Select Column']");

  // Click //li[normalize-space(.)='Last Name' and normalize-space(@role)='option']
  await page.click(
    "//li[normalize-space(.)='Last Name' and normalize-space(@role)='option']"
  );

  // Click div[role="presentation"] div[role="button"]
  await page.click('div[role="presentation"] div[role="button"]');

  // Click //li[normalize-space(.)='Employment Type' and normalize-space(@role)='option']
  await page.click(
    "//li[normalize-space(.)='Employment Type' and normalize-space(@role)='option']"
  );

  // Click //div[normalize-space(.)='Select Condition' and normalize-space(@role)='button']
  await page.click(
    "//div[normalize-space(.)='Select Condition' and normalize-space(@role)='button']"
  );

  // Click //li[normalize-space(.)='Equals' and normalize-space(@role)='option']
  await page.click(
    "//li[normalize-space(.)='Equals' and normalize-space(@role)='option']"
  );

  // Click //div[normalize-space(.)='Equals' and normalize-space(@role)='button']
  await page.click(
    "//div[normalize-space(.)='Equals' and normalize-space(@role)='button']"
  );

  // Click //div[normalize-space(.)='Select ConditionEqualsmatches any of' and normalize-space(@role)='presentation']/div[1]
  await page.click(
    "//div[normalize-space(.)='Select ConditionEqualsmatches any of' and normalize-space(@role)='presentation']/div[1]"
  );

  // Click //div[normalize-space(.)='​' and normalize-space(@role)='button']
  await page.click(
    "//div[normalize-space(.)='​' and normalize-space(@role)='button']"
  );

  // Click //li[normalize-space(.)='Part Time' and normalize-space(@role)='option']/*[local-name()="svg"]
  await page.click(
    "//li[normalize-space(.)='Part Time' and normalize-space(@role)='option']/*[local-name()=\"svg\"]"
  );

  // Click text="Apply"
  await page.click('text="Apply"');

  // Click //div[normalize-space(.)='employmentType == Part Time' and normalize-space(@role)='button']/*[local-name()="svg"]
  await page.click(
    "//div[normalize-space(.)='employmentType == Part Time' and normalize-space(@role)='button']/*[local-name()=\"svg\"]"
  );

  // ---------------------
  await context.close();
  await browser.close();
})();
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);
  });
});