DEV Community

Cover image for 🎨 Building Playwright Framework Step By Step - Create User Snippets
idavidov13
idavidov13

Posted on • Edited on

🎨 Building Playwright Framework Step By Step - Create User Snippets

🎯 Introduction

User snippets frequently go unnoticed in conversations about Automation Testing, yet I believe they represent a secret weapon in an automation tester's arsenal! πŸ”₯

πŸ’‘ What are User Snippets?: Custom code templates in VS Code or Windsurf that boost productivity and maintain consistency across your codebase

User snippets are a powerful tool for developers aiming to:

  • ⚑ Boost productivity - Reduce repetitive typing
  • 🎯 Maintain consistency - Ensure alignment with coding standards
  • πŸ“ˆ Enhance code quality - Follow best practices automatically
  • πŸš€ Save time - Insert complex code templates instantly

By defining your own snippets, you can ensure they align with your project's or team's coding standards and best practices, thus enhancing code quality and readability.

πŸ› οΈ How to Create User Snippets

Step 1: Access Snippets Configuration

πŸ“ Note: Instructions work for both VS Code and Windsurf

  1. Open Command Palette: Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (Mac)
  2. Search for: Preferences: Configure User Snippets
  3. Select: New Global Snippets file...
  4. Name your file: playwright-snippets.json

Step 2: Understanding Snippet Structure

Every snippet follows this JSON structure:

{
  "Snippet Name": {
    "scope": "typescript",
    "prefix": "trigger-word",
    "body": [
      "line 1 of code",
      "line 2 of code",
      "$1 // cursor position"
    ],
    "description": "What this snippet does"
  }
}
Enter fullscreen mode Exit fullscreen mode

πŸ” Key Components:

  • scope: Language where snippet works (typescript, javascript, etc.)
  • prefix: What you type to trigger the snippet
  • body: The actual code template (array of strings)
  • description: Helpful description for the snippet

🎯 Essential Playwright Snippets

{
    "Print to Console": {
        "scope": "javascript,typescript",
        "prefix": "cl",
        "body": [
            "console.log(${1});",
        ],
        "description": "Log output to the console"
    },
    "Playwright Describe": {
        "scope": "javascript,typescript",
        "prefix": "pwd",
        "body": [
            "test.describe('${1}', () => {${2}});",
        ],
        "description": "Generate a Playwright describe function"
    },
    "Playwright Test": {
        "scope": "javascript,typescript",
        "prefix": "pwt",
        "body": [
            "test('${1}',{tag:'@${2}'}, async ({ ${3} }) => {${4}});",
        ],
        "description": "Generate a Playwright test function"
    },
    "Playwright Test Step": {
        "scope": "javascript,typescript",
        "prefix": "pwts",
        "body": [
            "await test.step('${1}', async () => {${2}});",
        ],
        "description": "Generate a Playwright test step function"
    },
    "Expect toBeVisible": {
        "scope": "javascript,typescript",
        "prefix": "exv",
        "body": [
            "await expect(${1}).toBeVisible();",
        ],
        "description": "Generate expect locator to be visible code"
    },
    "Expect toEqual": {
        "scope": "javascript,typescript",
        "prefix": "exe",
        "body": [
            "await expect(${1}).toEqual(${2});",
        ],
        "description": "Generate expect recieved value to be equal to predefined value"
    },
    "Expect toHaveText": {
        "scope": "javascript,typescript",
        "prefix": "ext",
        "body": [
            "await expect(${1}).toHaveText(${2});",
        ],
        "description": "Generate expect locator to have predefined text"
    },
    "API Request": {
        "scope": "javascript,typescript",
        "prefix": "req",
        "body": [
            "const { status, body } = await apiRequest<${1}>({method:'${2}',url: '${3}', baseUrl: ${4}, body: ${5}, headers: ${6}}); expect(status).toBe(${7});",
        ],
        "description": "Generate API request"
    },
    "API Route": {
        "scope": "javascript,typescript",
        "prefix": "rou",
        "body": [
            "await page.route(`${1}`, async (route) => {await route.fulfill({status: 200, contentType: 'application/json',body: JSON.stringify(${2})});});"],
        "description": "Generate API route"
    },
    "Environment Variable": {
        "scope": "javascript,typescript",
        "prefix": "pr",
        "body": [
            "process.env.${1}",
        ],
        "description": "Generate environment variable"
    },
    "Intercept API Response":{
        "scope": "javascript,typescript",
        "prefix": "int",
        "body": [
            "const interceptedResponse = await page.waitForResponse(`${${1}}${2}`); const interceptedResponseBody = await interceptedResponse.json(); const ${3} = interceptedResponseBody.${4};",
        ],
        "description": "Intercept API response"
    },
    "Class for Page Object Model":{
        "scope": "javascript,typescript",
        "prefix": "pom",
        "body": [
            "import { Page, Locator, expect } from '@playwright/test';",
            "/**",
            " * This is the page object for the Home Page.",
            " * @export",
            " * @class ${1}",
            " * @typedef {${1}}",
            " */",
            "export class ${1}{",
            "    constructor(private page: Page) {}",
            "",
            "    get ${2} (): Locator {return ${3}};",
            "}",
        ],
        "description": "Class for Page Object Model"
    },
    "Getter for Class": {
        "scope": "javascript,typescript",
        "prefix": "ge",
        "body": [
            "get ${1}(): Locator {return this.page.${2};}",
        ],
        "description": "get locator"
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Pro Tips for Effective Snippets

⚑ Productivity Boosters:

🎯 Use Descriptive Prefixes - Find these, which work best for you

  • pwt for Playwright tests
  • req for API request
  • exv Assertion to be visible

πŸ“ Strategic Cursor Placement

Use ${1}, ${2}, ${3} etc. to define tab stops where you'll input specific values:

"body": [
  "test('${1}',{tag:'@${2}'}, async ({ ${3} }) => {${4}});"
  "});"
]
Enter fullscreen mode Exit fullscreen mode

πŸ”„ Include Common Patterns

Create snippets for:

  • 🎭 Boilerplate code (describe, test and test step blocks)
  • βœ… Assertions (expect)
  • πŸ” API Request/Intercept

🎯 What's Next?

In the next article we will dive into Environment Variables - managing configuration like a pro!

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


✨ Ready to supercharge your testing skills? Let's continue this journey 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

Hi @idavidov13
Once created, where to place file "playwright-snippets.json" ?

Thank You

Collapse
 
idavidov13 profile image
idavidov13

Hi, @shailendrakumaromkar πŸ‘‹
You don’t need to create the file in the repository. Follow the steps after you open your IDE:

  1. Open Command Palette: Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (Mac)
  2. Search for: Preferences: Configure User Snippets
  3. Select: New Global Snippets file...
  4. Name your file: nameTheFile and hit enter. After that, a blank file is opened nameTheFile.json. Paste the provided snippets and save it. Now you can safely close the file and create/open any file with .js or .ts extension. Enjoy snippets by typing the prefix. Depends of IDE, after you typed the prefix, you shoud hit enter or tab. If you have any issues, please let me know πŸ™