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

Jump to navigation Jump to search
m
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>

Navigation menu