Udemy Playwright: Web Automation Testing From Zero to Hero: Difference between revisions

Jump to navigation Jump to search
m
(5 intermediate revisions by the same user not shown)
Line 1,374: Line 1,374:


=== API Authentication ===
=== API Authentication ===
File <code>tests/auth.setup.ts</code> change to use API and save to file <code>.auth\user.json</code> env variable <code>ACCESS_TOKEN</code>
<nowiki>
setup("authentication", async ({ request }) => {
  const response = await request.post(
    "https://conduit-api.bondaracademy.com/api/users/login",
    {
      data: {
        user: {
          email: "conduit@dirksonline.net",
          password: "qB85R86#ZMKME$jVEVq#vJMDr*A!cJk",
        },
      },
    }
  )
  const responseBody = await response.json()
  const accessToken = responseBody.user.token
  user.origins[0].localStorage[0].value = accessToken
  fs.writeFileSync(authfile, JSON.stringify(user))
  process.env['ACCESS_TOKEN'] = accessToken</nowiki>
File <code>tests/workingWithAPI.spec.ts</code> remove all code for obtaining access token, and for specifying the access token header
File <code>playwright.config.ts</code> add <code>extraHTTPHeaders</code> node
<nowiki>
export default defineConfig({
  ... 
  use: {
    ...
    extraHTTPHeaders: {
      'Authorization': `Token ${process.env.ACCESS_TOKEN}`
    }</nowiki>
Notes:
* tried playwright@1.44.1 which still gives issues with the setup settings/file etc. continued using 1.43.0
* This relies on <code>.auth\user.json</code> existing with the correct format, but it is in .gitignore so a clean clone of repo will not work
* I do like how this now removes a lot of boiler code from test cases.
* I wonder, given that the auth header is now always included via the env variable, is the <code>.auth\user.json</code> still needed? (Might also need removing storageState values from the <code>playwright.config.ts</code>
== Section 8: Advanced ==
=== npm Scripts and CLI Commands ===
<nowiki>
npx playwright test usePageObjects.spec.ts --project=chromium
npx playwright show-report
npx playwright test usePageObjects.spec.ts --project=firefox
</nowiki>
In file: <code>package.json</code> add these to scripts node
<nowiki>
"pageObjects-chrome": "npx playwright test usePageObjects.spec.ts --project=chromium",
"pageObjects-firefox": "npx playwright test usePageObjects.spec.ts --project=firefox",
"pageObjects-all": "npm run pageObjects-chrome & npm run pageObjects-firefox"</nowiki>
<nowiki>
npm run pageObjects-chrome
npm run pageObjects-firefox
npm run pageObjects-all</nowiki>
Notes:
* && runs sequentially
* & runs parallely
* On windows npm scripts are executed in cmd.exe by default, use this to change it to bash <code>npm config set script-shell "C:/Program Files/Git/bin/bash.exe"</code>
=== Test Data Generator ===
Install faker with <code>npm i @faker-js/faker --save-dev --force</code> (force because it has several CVE's)
Update test in <code>tests\usePageObjects.spec.ts</code>
<nowiki>
test("Page Manger", async ({ page }) => {
  const pm = new PageManager(page)
  const randomFullName = faker.person.fullName({
    // sex: "male",      // specify sex (optional)
    // lastName: "Johns", // specify last name (optional)
  })
  const randomEmail = `${randomFullName.replace(/ /g, "")}${faker.number.int(
    1000
  )}@test.com`
  await pm.navigateTo().formLayoutsPage()
  await pm
    .onFormLayoutsPage()
    .submitUsingTheGridFormWithCredentialsAndSelectOption(
      "test@test.com",
      "Welcome1",
      "Option 2"
    )
  await pm
    .onFormLayoutsPage()
    .submitInLineFormWithNameEmailAndCheckbox(randomFullName, randomEmail, true)
  await pm.navigateTo().datePickerPage()
  await pm.onDatePickerPage().selectCommonDatePickerDateFromToday(10)
  await pm.onDatePickerPage().selectDatePickerWithRangeFromToday(6, 15)
})</nowiki>
Notes:
* The faker fullName() method can sometimes add title prefixes, suffixes, etc., which look very odd in email addresses ....
=== Test Retries ===
* workers are clean incognito browser windows
* worker is re-used after completing a passing test
* a new worker is started after a failed test
* with retries on the failed test is retried in the new worker
* with retries off the next test is started in the new worker
In file <code>playwright.config.ts</code>
<nowiki>
export default defineConfig({
  ...
  /* Retry on CI only */
  retries: process.env.CI ? 2 : 1,
  use: {
    ...
    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: "on-first-retry", //['on-first-retry', 'on-all-retries', 'off', 'on', 'retain-on-failure']
  },
</nowiki>
In file <code>tests\uiComponents.spec.ts</code>
<nowiki>
test.describe.only("Forms Layouts page", () => {
  test.describe.configure({ retries: 2,  })
  test.beforeEach(async ({ page }, testInfo) => {
    if(testInfo.retry){
      // can clean up from previous failed attempt
    }
    ...
  })
...
</nowiki>
Notes:
* Having trace on-first-retry is very cool
=== Parallel Execution ===
=== Screenshots and Videos ===
=== Environment Variables ===
=== Configuration File ===
=== Fixtures ===
=== Project Setup and Teardown ===
=== Test Tags ===
=== Mobile Device Emulator ===
=== Reporting ===
=== Visual Testing ===
=== Playwright with Docker Container ===
=== Github Actions and Argos CI ===

Navigation menu