npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@kinosuke01/eslint-plugin-playwright-pom

v0.0.1

Published

ESLint plugin that enforces Page Object Model (POM) pattern for Playwright tests

Downloads

28

Readme

eslint-plugin-playwright-pom

ESLint plugin that enforces Page Object Model (POM) pattern for Playwright tests, including proper directory structure, separation of concerns, and robust element selection strategies.

Table of Contents


📦 NPM Package Usage

Installation

npm install --save-dev @kinosuke01/eslint-plugin-playwright-pom

Configuration

ESLint Flat Config (eslint.config.js)

import playwrightPom from '@kinosuke01/eslint-plugin-playwright-pom';

export default [
  {
    plugins: {
      'playwright-pom': playwrightPom
    },
    rules: {
      ...playwrightPom.configs.recommended.rules
    }
  }
];

Legacy Config (.eslintrc.json)

{
  "plugins": ["@kinosuke01/playwright-pom"],
  "rules": {
    "@kinosuke01/playwright-pom/directory-structure": "error",
    "@kinosuke01/playwright-pom/allow-assertions-only-in-flows": "error",
    "@kinosuke01/playwright-pom/allow-locators-only-in-pages": "error",
    "@kinosuke01/playwright-pom/discourage-locators": "warn"
  }
}

Rules

This plugin provides 4 rules to enforce the Page Object Model pattern:

1. directory-structure (error)

Enforces strict directory structure and naming conventions for Playwright test files.

This rule ensures that your test codebase follows a clear, organized structure:

  • Test specs (*.spec.ts) → Must be in tests/flows/ directory
  • Page Objects (*-page.ts) → Must be in tests/pages/ directory
  • Fixtures (*-fixture.ts) → Must be in tests/fixtures/ directory
  • Helpers → Must be in tests/helpers/ directory with kebab-case naming

Examples:

// ✅ Valid - Test spec in flows directory
// tests/flows/login.spec.ts
import { test } from '@playwright/test';

// ✅ Valid - Page Object in pages directory
// tests/pages/login-page.ts
export class LoginPage {}

// ✅ Valid - Fixture in fixtures directory
// tests/fixtures/user-fixture.ts
export const userFixture = test.extend({});

// ✅ Valid - Helper with kebab-case naming
// tests/helpers/date-formatter.ts
export function formatDate() {}

// ❌ Invalid - Spec file not in flows/
// tests/login.spec.ts

// ❌ Invalid - Page Object not in pages/
// tests/login-page.ts

// ❌ Invalid - Wrong naming convention
// tests/pages/LoginPage.ts (should be login-page.ts)

2. allow-assertions-only-in-flows (error)

Prohibits the use of assertions (expect) outside of test flow files.

This rule enforces separation of concerns by ensuring:

  • Test assertions are only written in tests/flows/ (test spec files)
  • Page Objects focus on returning values and encapsulating page interactions
  • Clear boundary between test logic and page abstraction

Why? Page Objects should be reusable and testable independently. Embedding assertions in Page Objects couples them to specific test expectations, reducing reusability.

Examples:

// ✅ Valid - Assertions in test flow
// tests/flows/login.spec.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages/login-page';

test('user can login', async ({ page }) => {
  const loginPage = new LoginPage(page);
  await loginPage.navigate();
  await loginPage.login('[email protected]', 'password');

  expect(await loginPage.getWelcomeMessage()).toBe('Welcome!');
});

// ✅ Valid - Page Object returns data for testing
// tests/pages/login-page.ts
export class LoginPage {
  async getWelcomeMessage() {
    return await this.page.locator('[data-testid="welcome"]').textContent();
  }
}

// ❌ Invalid - Assertion in Page Object
// tests/pages/login-page.ts
import { expect } from '@playwright/test'; // ❌ Error: expect import outside flows/

export class LoginPage {
  async verifyLogin() {
    expect(this.page.url()).toContain('/dashboard'); // ❌ Error: assertion outside flows/
  }
}

3. allow-locators-only-in-pages (error)

Restricts element locator methods to Page Objects only.

This rule enforces the core POM principle: element selection logic must be encapsulated in Page Objects.

Restricted methods (only allowed in tests/pages/):

  • locator()
  • getByRole()
  • getByTestId()
  • getByText()
  • getByLabel()
  • getByPlaceholder()
  • getByAltText()
  • getByTitle()
  • querySelector() / querySelectorAll()
  • $() / $$()

Benefits:

  • Maintainability: When UI changes, update only Page Objects
  • Reusability: Same page methods across multiple tests
  • Readability: Tests express business logic, not DOM queries

Examples:

// ✅ Valid - Locators in Page Object
// tests/pages/login-page.ts
export class LoginPage {
  constructor(private page: Page) {}

  get emailInput() {
    return this.page.getByTestId('email-input');
  }

  get passwordInput() {
    return this.page.getByTestId('password-input');
  }

  get submitButton() {
    return this.page.getByRole('button', { name: 'Sign in' });
  }

  async login(email: string, password: string) {
    await this.emailInput.fill(email);
    await this.passwordInput.fill(password);
    await this.submitButton.click();
  }
}

// ✅ Valid - Test uses Page Object methods
// tests/flows/login.spec.ts
test('user can login', async ({ page }) => {
  const loginPage = new LoginPage(page);
  await loginPage.login('[email protected]', 'password123');
});

// ❌ Invalid - Direct locator usage in test
// tests/flows/login.spec.ts
test('user can login', async ({ page }) => {
  await page.getByTestId('email-input').fill('[email protected]'); // ❌ Error
  await page.getByTestId('password-input').fill('password123'); // ❌ Error
  await page.getByRole('button', { name: 'Sign in' }).click(); // ❌ Error
});

4. discourage-locators (warn)

Discourages fragile element locator methods in favor of robust selection strategies.

This rule promotes using locators that are resilient to UI changes.

Recommended methods:

  • getByRole() - Based on ARIA roles, semantic and accessible
  • getByTestId() - Explicit test identifiers, stable across changes

Discouraged methods (generates warnings):

  • ⚠️ locator() - Generic CSS/XPath, can be fragile
  • ⚠️ getByText() - Breaks when copy changes
  • ⚠️ getByLabel() - Dependent on label text
  • ⚠️ getByPlaceholder() - Dependent on placeholder text
  • ⚠️ getByAltText() - Dependent on alt text
  • ⚠️ getByTitle() - Dependent on title attribute
  • ⚠️ querySelector() / querySelectorAll() - Low-level DOM queries
  • ⚠️ $() / $$() - Playwright shorthand for querySelector

Examples:

// ✅ Recommended - Using getByRole
await page.getByRole('button', { name: 'Submit' }).click();

// ✅ Recommended - Using getByTestId
await page.getByTestId('submit-button').click();

// ⚠️ Warning - Using getByText (fragile against copy changes)
await page.getByText('Submit').click();

// ⚠️ Warning - Using generic locator
await page.locator('.submit-btn').click();

// ⚠️ Warning - Using querySelector
await page.querySelector('.submit-btn').click();

Why these recommendations?

  • getByRole() aligns with accessibility best practices
  • getByTestId() provides stable, explicit test hooks
  • Text-based selectors break when copy/translations change
  • CSS selectors break when styling refactors occur

Directory Structure

The recommended directory structure enforced by this plugin:

tests/
├── flows/              # Test specification files
│   ├── login.spec.ts
│   └── checkout.spec.ts
├── pages/              # Page Object classes
│   ├── login-page.ts
│   ├── home-page.ts
│   └── checkout-page.ts
├── fixtures/           # Test fixtures
│   └── user-fixture.ts
└── helpers/            # Utility functions
    ├── date-formatter.ts
    └── data-generator.ts

Example: Complete Login Flow

// tests/pages/login-page.ts
import type { Page } from '@playwright/test';

export class LoginPage {
  constructor(private page: Page) {}

  async navigate() {
    await this.page.goto('/login');
  }

  async login(email: string, password: string) {
    await this.page.getByTestId('email-input').fill(email);
    await this.page.getByTestId('password-input').fill(password);
    await this.page.getByRole('button', { name: 'Sign in' }).click();
  }

  async getErrorMessage() {
    return await this.page.getByTestId('error-message').textContent();
  }
}

// tests/flows/login.spec.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages/login-page';

test.describe('Login Flow', () => {
  test('should login successfully with valid credentials', async ({ page }) => {
    const loginPage = new LoginPage(page);
    await loginPage.navigate();
    await loginPage.login('[email protected]', 'password123');

    await expect(page).toHaveURL('/dashboard');
  });

  test('should show error with invalid credentials', async ({ page }) => {
    const loginPage = new LoginPage(page);
    await loginPage.navigate();
    await loginPage.login('[email protected]', 'wrongpassword');

    expect(await loginPage.getErrorMessage()).toContain('Invalid credentials');
  });
});

🛠️ Developer Guide

Development Setup

  1. Clone the repository

    git clone https://github.com/kinosuke01/eslint-plugin-playwright-pom.git
    cd eslint-plugin-playwright-pom
  2. Install dependencies

    npm install
  3. Build the project

    npm run build

Available Scripts

| Script | Command | Description | |--------|---------|-------------| | Build | npm run build | Compile TypeScript to JavaScript using tsup | | Lint | npm run lint | Check code quality with Biome | | Lint Fix | npm run lint:fix | Auto-fix linting issues | | Test | npm run test | Run tests once with Vitest | | Test Watch | npm run test:watch | Run tests in watch mode | | Test Coverage | npm run test:coverage | Generate test coverage report |

Testing

This project uses Vitest for testing.

Run all tests:

npm test

Run tests in watch mode during development:

npm run test:watch

Generate coverage report:

npm run test:coverage

Test files are co-located with source files following the pattern *.test.ts.

Building

The project uses tsup for building:

npm run build

This generates:

  • dist/index.js - CommonJS output
  • dist/index.mjs - ESM output
  • dist/index.d.ts - TypeScript declarations

The build is automatically run before publishing via the prepublishOnly hook.

Project Structure

eslint-plugin-playwright-pom/
├── src/
│   ├── index.ts                              # Plugin entry point
│   └── rules/
│       ├── directory-structure.ts            # Directory/naming enforcement
│       ├── allow-assertions-only-in-flows.ts # Assertion restriction
│       ├── allow-locators-only-in-pages.ts   # Locator restriction
│       └── discourage-locators.ts            # Locator recommendation
├── dist/                                      # Build output (gitignored)
├── package.json
├── tsconfig.json
└── README.md

License

MIT

Author

kinosuke01