DEV Community

Cover image for πŸ”§ Building Playwright Framework Step By Step - Implementing POM as Fixture and Auth User Session
idavidov13
idavidov13

Posted on • Edited on

πŸ”§ Building Playwright Framework Step By Step - Implementing POM as Fixture and Auth User Session

🎯 Introduction

Fixtures in Playwright provide a powerful mechanism to set up the environment for your tests, manage resources, and share common objects or context across multiple tests! πŸš€ These reusable components allow you to define custom setup and teardown procedures that automate the preparation and cleanup processes, ensuring a consistent testing environment and optimizing your workflows.

πŸ’‘ What are Fixtures?: Think of fixtures as your testing toolkit - they provide the foundation and tools your tests need to run consistently and efficiently.

βœ… Prerequisites

This article builds directly on the concepts from previous ones. To get the most out of it, you should have:

πŸ› οΈ Implement POM (Page Object Model) as Fixture

πŸ“ Create Fixtures Folder

Create fixtures/pom folders in the root directory of the project.

project-root/ β”œβ”€β”€ fixtures/ β”‚ └── pom/ β”‚ β”œβ”€β”€ page-object-fixture.ts β”‚ └── test-options.ts β”œβ”€β”€ tests/ └── playwright.config.ts 
Enter fullscreen mode Exit fullscreen mode

🎭 Create Fixtures Files

Create and implement fixtures for the client site for all pages of the application.

πŸ”§ Page Object Fixture

  • page-object-fixture.ts: This file is used for extending the test fixture from @playwright/test
import { test as base } from '@playwright/test'; import { HomePage } from '../../pages/clientSite/homePage'; import { NavPage } from '../../pages/clientSite/navPage'; import { ArticlePage } from '../../pages/clientSite/articlePage'; export type FrameworkFixtures = { homePage: HomePage; navPage: NavPage; articlePage: ArticlePage; }; export const test = base.extend<FrameworkFixtures>({ homePage: async ({ page }, use) => { await use(new HomePage(page)); }, navPage: async ({ page }, use) => { await use(new NavPage(page)); }, articlePage: async ({ page }, use) => { await use(new ArticlePage(page)); }, }); export { expect } from '@playwright/test'; 
Enter fullscreen mode Exit fullscreen mode

βš™οΈ Test Options Configuration

  • test-options.ts: This file is used for merging all extended test fixtures
import { test as base, mergeTests } from '@playwright/test'; import { test as pageObjectFixture } from './page-object-fixture'; const test = mergeTests(pageObjectFixture); const expect = base.expect; export { test, expect }; 
Enter fullscreen mode Exit fullscreen mode

πŸ” Implement Auth User Session

🎯 Strategic Advantage: Leveraging authenticated user sessions in Playwright is a strategic approach to streamline testing of password-protected applications!

This method involves pre-creating and reusing authentication tokens or session information, allowing automated tests to bypass the login UI. It significantly reduces the time and resources required for tests that need an authenticated user context, enhancing test efficiency and reliability.

🌟 Advantages of Using Authenticated User Sessions in Playwright:

  • ⚑ Speed: Directly using authenticated sessions eliminates the overhead of navigating through login screens for each test, accelerating the test execution process
  • πŸ›‘οΈ Stability: Tests become less prone to failures related to UI changes in the authentication flow, increasing their reliability
  • 🎯 Focus: Allows tests to concentrate on the core functionalities that require authentication, rather than the login process itself, making them more targeted and concise

πŸ“ Create Auth Script File

Create auth.setup.ts file in the test directory of the project.

import { test as setup } from '../fixtures/pom/test-options'; setup('auth user', async ({ homePage, navPage, page }) => { await setup.step('create logged in user session', async () => { await homePage.navigateToHomePageGuest(); await navPage.logIn(process.env.EMAIL!, process.env.PASSWORD!); await page.context().storageState({ path: '.auth/userSession.json' }); }); }); 
Enter fullscreen mode Exit fullscreen mode

βš™οΈ Update Configuration File

Add the following configuration to your playwright.config.ts:

projects: [ { name: 'setup', use: { ...devices['Desktop Chrome'], viewport: { width: 1366, height: 768 }, }, testMatch: /.*\.setup\.ts/, }, { name: 'chromium', use: { ...devices['Desktop Chrome'], storageState: '.auth/userSession.json', viewport: { width: 1366, height: 768 }, }, dependencies: ['setup'], }, { name: 'firefox', use: { ...devices['Desktop Firefox'] }, }, { name: 'webkit', use: { ...devices['Desktop Safari'] }, }, ], 
Enter fullscreen mode Exit fullscreen mode

πŸ”’ Add File to .gitignore

⚠️ Security Best Practice: Add userSession.json file to .gitignore file in the root directory of the project.

# Authentication User file userSession.json 
Enter fullscreen mode Exit fullscreen mode

πŸƒβ€β™‚οΈ Create Auth User Session

Run the auth.setup.ts file to create auth user session:

npx playwright test auth.setup.ts 
Enter fullscreen mode Exit fullscreen mode

πŸ‘€ Create Guest User Session

Create guestSession.json file in the .auth directory of the project and add {} to it.

πŸ’‘ Guest Sessions: Empty JSON object represents an unauthenticated state for tests that require guest access.

🎯 What's Next?

In the next article we will implement UI Tests - bringing your framework to life with comprehensive user interface testing!

πŸ’¬ Community: Please feel free to initiate discussions on this topic, as every contribution has the potential to drive further refinement.


✨ Ready to enhance your testing capabilities? Let's continue building this robust framework together!


πŸ™πŸ» Thank you for reading! Building robust, scalable automation frameworks is a journey best taken together. If you found this article helpful, consider joining a growing community of QA professionals πŸš€ who are passionate about mastering modern testing.

Join the community and get the latest articles and tips by signing up for the newsletter.

Top comments (2)

Collapse
 
shailendrakumaromkar profile image
Shailendra Omkar • Edited

Hi @idavidov13

After running command - npx playwright test auth.setup.ts
getting below error
looks like it is pointing to staging env url but I am not sure how to create account in staging env and get the URL, API_URL for staging env ?

Although I have created account in conduit.bondaracademy.com/

Do I need to create empty "userSession.json" file manually
or
It should have user session details stored in it after running above command ?

Error: page.goto: net::ERR_NAME_NOT_RESOLVED at staging.conduit.bondaracademy.com/
Call log:

  • navigating to "staging.conduit.bondaracademy.com/", waiting until "networkidle" at ..\pages\clientSite\homePage.ts:35 33 | */ 34 | async navigateToHomePageGuest(): Promise { > 35 | await this.page.goto(process.env.URL as string, { | ^ 36 | waitUntil: 'networkidle', 37 | });
Collapse
 
idavidov13 profile image
idavidov13

Hi @shailendrakumaromkar
The issue is caused by the wrong URL you’re trying to navigate to. I add to the notes that the data in .env.stage is only for demonstration purposes.