QA Interview Hub · Knowledge base · Quizzes · Українська

Patterns

SOLID, DRY, KISS in tests, and anti-patterns

SOLID in a test framework

SOLID in a test framework means a change in one place does not break another and swapping a part does not force rewriting the consumer. A Page Object describes the UI, a factory the data, an API client the requests, and tests get dependencies through fixtures. Typical smells: a bloated ApiClient, a page subclass changing the meaning of open(). Real variability justifies an abstraction, not a wish for purity.

Patterns · Principles

An ApiClient with two hundred methods and it is edited every Monday. Which principle is violated?

SOLID was invented for object-oriented code, but a test framework is code too, read and changed for years. Its classes grow by the same laws: a page that knows about the DB, a client that grows with every new requirement, a subclass that breaks the parent's expectations. SOLID gives names to these pains. One caveat: in tests simplicity and readability matter more than the purity of a pattern.

How it works and why. All five principles are about one thing: a change in one place must not break another, and swapping a part must not require rewriting the consumer. The table shows their embodiment in test code and the smell of a violation.

PrincipleIn a test frameworkA smell of violation
SA Page Object describes the UI, a factory the data, an API client the requestsA Page Object creates a user in the DB itself
OA new login method is a new class or a key in a dictionaryA switch on the mode in ten places
LA page subclass can stand where the base one is expectedA subclass overrides open() and changes its meaning
ISmall interfaces: PaymentsApi, UsersApiAn ApiClient with two hundred methods
DA test depends on a fixture, not on a way to log innew LoginPage(page).loginAs(...) in every test

S: one reason to change. A Page Object that also prepares data in the DB changes both when the markup changes and when the DB schema changes. Data should be prepared by a factory or a fixture:

// before: a Page Object also prepares data
class TransferPage {
  async seedUser() {
    await db.query('insert into users(email) values ($1)', [email]);
  }
}

// after: a fixture prepares data, the page only describes the UI
export const test = base.extend<{ user: User }>({
  user: async ({ request }, use) => {
    const user = await createUserViaApi(request);
    await use(user);
    await deleteUserViaApi(request, user);
  },
});

L: a subclass can be substituted. If ReportsPage extends BasePage, then wherever open() of the base page is called, the subclass must behave the same. Deep page hierarchies often violate this:

class BasePage {
  protected readonly path: string = '/';
  constructor(protected readonly page: Page) {}

1  async open() {
    await this.page.goto(this.path);
  }
}

class ReportsPage extends BasePage {
  protected readonly path = '/reports';

  // breaks the contract: after open() the page is no longer opened from scratch
2  async open() {
    await this.page.getByRole('link', { name: 'Reports' }).click();
  }
}
  1. The contract of the base open(): navigate to the address, so one can start from an empty tab.
  2. The subclass requires the user to already be on another page with a link. A call new ReportsPage(page).open() from a clean state will fail.

The fix: do not override open() with a different meaning; give navigation a separate method, or replace inheritance with composition.

D: depend on an abstraction. In Playwright fixtures implement it naturally: a test asks for “a logged-in admin page”, and how it became one (a form, an API, a saved state) is decided by the fixture.

// depends on the way to log in
test('lists transfers', async ({ page }) => {
  await new LoginPage(page).loginAs(admin);
  await page.goto('/transfers');
});

// depends on an abstraction: a fixture that provides a logged-in page
test('lists transfers', async ({ adminPage }) => {
  await adminPage.goto('/transfers');
});

O is shown in the Strategy example: a new login method is added as a class, not by editing a switch. I means splitting a bloated ApiClient into PaymentsApi, UsersApi that share one request: a test depends only on what it needs.

Limits and alternatives. Here the difference from production code applies: tests must be simple, and an abstraction is justified by real variation or the pain of change. In TypeScript structural typing makes interfaces cheap, and Playwright fixtures provide DI, so a dependency container is usually not needed.

How much abstraction is appropriate

Wrong

A principle for its own sake

An interface with one implementation and three layers for a five-line test.

Right

A principle where there is variation

An abstraction appears when a second implementation or the pain of change shows up.

Figure 1. A principle is justified by the problem it removes.

Common mistakes.

  • An interface with one implementation “just in case”: a layer that only complicates navigation.
  • A base page class that grows into a “God Page”: everything that might be needed in several places lands in it.
  • Inheritance for code reuse instead of composition: the subclass inherits unrelated methods too.
  • A factory that reaches into the DB in the constructor: it violates SRP and makes every test pay for the extra.
  • A dependency container on top of Playwright fixtures: a double DI mechanism.

Check yourself

AdminPage extends BasePage but AdminPage.open() does not call goto, it clicks a menu link. Which principle is violated and why can a test fail?

Answer

Liskov: the subclass cannot stand in for the base class. Code that calls open() from a clean state relies on goto, while a click on a link needs an already opened page with a menu.

Why does 'Dependency Inversion' in Playwright usually not need a dependency container?

Answer

Fixtures are already built-in DI: a test declares what it needs, and Playwright creates the dependencies in the right order and cleans them up after the test. An extra container would only duplicate this mechanism.

In an interview. Junior: The most important in tests for me are SRP and Dependency Inversion: each class does one thing, and tests get dependencies through fixtures. Middle/Senior: I apply the rest when there is real variation or the pain of change, not for the sake of a template. I check Liskov on page hierarchies: if a subclass changes the meaning of open(), I replace inheritance with composition. I do not add an abstraction for one implementation.

DRY vs DAMP and KISS

DRY demands one place for every piece of knowledge, while DAMP says a test should read on its own even at the cost of repetition. Hence the split: DRY for infrastructure (locators, steps, fixtures) and DAMP for the test body, where inputs and expectations stay visible. Extract what changes together, not merely identical lines. KISS adds that abstractions are not built in advance and branching logic is kept out of tests.

Patterns · Principles

To understand what a test checks you need to open three files. Where is the excess DRY?

The test “transfer limit” is one line, runScenario(page, SCENARIOS[3]). Duplication is zero, but to learn what exactly is checked you open the helper and the array and count an index. When such a test fails the report says “limit” and nothing else. This is the case where DRY went too far. The lesson is about where repetition hurts and where it helps.

How it works and why. DRY (Don't Repeat Yourself) demands that every fact has one place in the system. The word “fact” matters: it is not about identical lines but about identical knowledge. The locator of the “Confirm” button is knowledge about the markup, and it should live in one place. But that the limit test uses the amount 50,001 is not repeated knowledge, it is an input value, the substance of this test. DAMP (Descriptive And Meaningful Phrases) says a test must read on its own, even at the cost of repetition. Hence the split: DRY for infrastructure, DAMP for the test body.

What goes where

Infrastructure: DRYlocators, steps, fixtures, factoriesThe test body: DAMPthe inputs and expectations are visible at onceLogic in a test: noif, loops with conditions: a test is linear
Figure 1. Infrastructure is shared, the test body exposes data, and logic stays out of the test.

Example: before and after. Before (too DRY):

test('limit', async ({ transferPage }) => {
  await runScenario(transferPage, SCENARIOS[3]);
});

To understand what is checked you must open two files. After (DAMP): the three steps and the expectation sit in the test itself, while locators and buttons stay in transferPage.

test('blocks a transfer above the daily limit', async ({ transferPage }) => {
  await transferPage.fill('UA002', 50_001);
  await transferPage.confirm();
  await expect(transferPage.error).toHaveText('Daily limit exceeded');
});

Parametrisation. A loop over an array of cases with test() inside is also fine, provided each case has a clear name and visible data. Two marks:

const cases = [
1  { name: 'blocks above the daily limit', amount: 50_001, error: 'Daily limit exceeded' },
  { name: 'rejects zero', amount: 0, error: 'Amount must be positive' },
  { name: 'rejects negative', amount: -5, error: 'Amount must be positive' },
];

for (const c of cases) {
2  test(c.name, async ({ transferPage }) => {
    await transferPage.fill('UA002', c.amount);
    await transferPage.confirm();
    await expect(transferPage.error).toHaveText(c.error);
  });
}
  1. Each case describes data and expectation side by side: in the report it is a separate test with its own name.
  2. The loop body is linear: no if and branches, so all the cases behave the same.

KISS and YAGNI. Keep It Simple: do not build an abstraction “for the future”. Three tests with the same two lines are not yet a reason for a new layer: first the rule of three, and only when knowledge is duplicated, not a coincidence. Logic in tests (if, loops with conditions) is a signal too: a test must be linear, otherwise it is hard to say what it checks.

// logic in a test: which path runs depends on the state
if (await banner.isVisible()) {
  await banner.getByRole('button', { name: 'Close' }).click();
}

// better: the state is fixed by a precondition, the test is linear
await expect(banner).toBeHidden();

Limits and alternatives. The criterion for extraction is simple: if a change in one place must change all the copies, it is shared knowledge and must not be duplicated (DRY). If different tests repeat a line because each needs its own value, keep the repetition (DAMP). A helper that hides expectations risks becoming a “black box”: it needs a clear name, and the check stays in the test.

Too DRY versus DAMP

Too DRY

Data hidden in a table

To understand what the test checks you open two files and count an index.

DAMP

Data visible in the test

The name, the input and the expectation read together. Only what is the substance of the test repeats.

Figure 2. The number of lines is not the criterion: the criterion is whether the substance of the test is visible.

Common mistakes.

  • Extracting everything repeated into a helper, including the inputs and expectations: the test stops being readable and a failure does not explain itself.
  • Merging different tests into one parametrised “universal” one with flags: logic appears in the test.
  • An abstraction after two repetitions: apply the rule of three and first make sure it is one piece of knowledge.
  • Copying locators into every test for “readability”: that is no longer DAMP but duplication of knowledge about the markup.
  • A loop with test() without unique names: Playwright stops the run with a duplicate test title error, and no test starts.

Check yourself

Which part of a test should repeat (DAMP) and which live in one place (DRY)? Give an example of each.

Answer

DRY: the locator of the “Confirm” button, the login steps, a data factory: knowledge that changes together. DAMP: the amount 50,001 and the expected message “Daily limit exceeded”: the input and the result that are the substance of the test.

A test has if (await banner.isVisible()) close the banner. Why is it a problem and what to do?

Answer

The execution path depends on the state, so the test is non-deterministic and it is unclear what it checks. Fix the state with a precondition (a consent cookie or a fixture) and then assert that the banner is absent.

In an interview. Junior: I write infrastructure (locators, steps, fixtures) by DRY, and the tests themselves by DAMP so the data and expectations are visible without jumping to other files. Middle/Senior: DRY is about knowledge, not lines, so I extract only what changes together. I add an abstraction by the rule of three and when duplication has become real pain. In tests I avoid logic: I replace branches with preconditions.

Typical antipatterns in frameworks

A framework antipattern is a solution that looks reasonable and later does harm. Examples: god objects, deep inheritance, shared mutable state, waitForTimeout, assertions in helpers. They boil down to structure, state, time and clarity. They are named through cause and effect, fixed one at a time and the effect measured. A deliberate, limited, documented decision, such as a serial group, is not an antipattern.

Patterns · Antipatterns

The framework grew: runs are slow and flakes multiply. What is wrong in its architecture?

An antipattern is a typical solution that looks reasonable and later does harm. Test frameworks have few of them, and they repeat from project to project, so it is worth being able to name them, explain the damage and propose a replacement. An interviewer usually expects not a list of terms but an explanation of how they show up (flakes, slow runs, painful PRs) and what is done about them.

How it works and why. All antipatterns boil down to four causes. Structure: god objects, deep inheritance, wrappers over wrappers. State: shared variables and constants, test order as a dependency; in Playwright tests are isolated because they run in parallel and may restart, so a dependency on order will not survive. Time: hard waits with waitForTimeout instead of web-first assertions and auto-waiting. Clarity: assertions without purpose in helpers, logic in tests, abstraction for growth. The table puts them together.

AntipatternThe damageInstead
God Page Object / God HelperEverything in one place: PR conflicts, unclear responsibilityComponents, small modules by domain
Deep inheritanceA subclass inherits what is not its own and breaks the parent's expectationsComposition
Shared mutable stateTest order becomes a dependency, parallelism breaks itData per test, fixtures
waitForTimeoutSlow and does not guarantee a stateWeb-first assertions, auto-waiting
Assertions in helpersTen silent checks: unclear what failedExpectations in the test
A wrapper over a wrapperHides the API, degrades the traceDirect locators, a wrapper only with value
Logic in a testA non-deterministic pathA fixed precondition
Constants that get mutatedOne test spoils data for othersA factory returning a new object
Abstraction for growthA layer for 20 tests nobody asked forSimple code first, the rule of three

Example 1: a wrapper over a wrapper. A custom click() that calls locator.click() with no added value hides API capabilities (options, force, timeout) and degrades the trace:

// a wrapper with no value: hides locator.click() and its options
async function click(page: Page, selector: string) {
  await page.locator(selector).click();
}

// a direct call: all the options, the trace shows the real line
await page.getByRole('button', { name: 'Confirm' }).click({ timeout: 5_000 });

Example 2: constants that get mutated. One test changes a shared constant, and the next ones get a spoiled state. A dependency on test order arrives quietly:

// a shared constant: a test changes it, the next ones see the change
export const USER = { email: 'qa@example.com', role: 'user' };

test('promotes the user', async () => {
  USER.role = 'admin';
});

// a function: every call gives a new object
export const makeUser = () => ({ email: 'qa@example.com', role: 'user' });

A wrapper: when it is real

Wrong

A wrapper for its own sake

click(page, selector) adds nothing and hides the options and the call line in the trace.

Right

A wrapper with value

A page method confirmTransfer() combines several actions under a business name in test.step.

Figure 1. A wrapper is justified when it adds value: a business name, several actions, reporting.

Limits and alternatives. An antipattern is not always an error in every context: waitForTimeout is sometimes left deliberately for debugging, and shared state in a serial group is a conscious agreement. The difference is that the decision is explicit, limited and written down, not an accidental consequence. And conversely, over-fighting antipatterns also hurts: rewriting working code because of a term is not worth it while there is no real pain.

How to talk about it at an interview. Do not just list them but show the cause-and-effect chain and the measure. A hypothetical example: a base class with sixty methods is cut into components (a header, a table), login is moved to storageState, and the effect is measured before and after: run time, the number of PR conflicts, the share of flakes.

Common mistakes.

  • Only listing terms without explaining the damage: the answer sounds memorised.
  • Treating waitForTimeout with a larger timeout: that hides the symptom while the race remains.
  • Cutting a god object into several equally bloated ones: the structure changed, the problem stayed.
  • Seeing an antipattern where the decision is conscious and limited, and rewriting for no benefit.
  • Fixing all antipatterns in one big PR: risky and hard to review; better one at a time, measuring the effect.

Check yourself

Tests pass one by one but with --workers=4 some fail. Which two antipatterns from the table to check first?

Answer

Shared mutable state (module variables, constants that tests mutate) and dependency on execution order. In a parallel run tests land in different workers where this data is separate or the order is different.

A colleague added a utility click(page, selector) and explained it is a single point of change. Is it an antipattern?

Answer

Yes, if it only calls locator.click(): there is no value, and the options and a clear line in the trace are lost. A wrapper is justified when it adds value: a business name, several actions, test.step.

In an interview. Junior: The antipatterns I name most often are god objects, deep inheritance, shared state between tests and hard timeouts. They are fixed with components, fixtures, isolated data and web-first assertions. Middle/Senior: I explain an antipattern through cause and effect: shared state gives flakes in parallel, a god object gives PR conflicts. I fix them one at a time and measure the effect: run time, the share of flakes. A conscious, limited decision (for example a serial group) I do not count as an antipattern.

Test code as production code: review, linters and metrics

Test code is maintained like production code: review asks whether a test can fail, a linter catches mechanical errors, and metrics show a trend. Metrics: share of flaky tests, run time, switched-off tests, cost of change. They are not a plan, because then the measure is «met» by deleting tests.

Patterns · Test code quality

A test failed on Friday, and the file has 400 lines, a 5-second pause and a commented-out assertion. What does such a «temporary» fix cost?

Test code lives for years, it is read more often than written, and when it fails, the pipeline of the whole team stops. Yet test review often boils down to «it works, merge», and the linter is switched off for test folders. The result is familiar: the suite grows, flaky tests multiply, and trust in a red run disappears. This lesson is about carrying over to tests the same practices as for production code, and about what to measure.

Mechanism: why a test costs more than its size. A test has no value of its own unless the team trusts it. Every unstable test takes time from everyone who sees a red run: they have to find out whether it is a defect or noise. So the cost of a bad test is multiplied by the number of people and runs, not by the number of lines. Three practices follow: check a test before the merge (review), catch typical mistakes automatically (linter, types, config settings) and watch the state of the suite with numbers.

Three gates for a test

A test changethe author sees a green run1. Linter and tsc (machine)await, pause, force, .only2. Review (person)can this test fail at all3. CI and metricsforbidOnly, flaky share, run timewhat slips through costs the whole team
Figure 1. Each gate catches its own kind: the machine removes the mechanical, meaning stays with a person.

Reviewing a test. The questions differ from reviewing production code, because the first one is: can this test fail.

  • Does the assertion check behaviour, not only that a step was executed? A test without an assertion is always green. A useful trick: temporarily break the code or the expected value and make sure the test turns red.
  • Is the test isolated: its own data, no dependence on order, cleanup after itself?
  • Are there no fixed pauses, force, if branches and loops inside the test that hide what is being checked?
  • Does the title read like a requirement («rejects an expired card»), not like an implementation?
  • Is repeated code moved to a fixture or Page Object, but without premature abstraction (see the lesson on DRY and DAMP)?

Linter and types. What a machine can check should not be left to the reviewer. For Playwright there is the eslint-plugin-playwright plugin: its recommended set includes the rules missing-playwright-await (a forgotten await), no-wait-for-timeout, no-force-option, no-focused-test and no-skipped-test, expect-expect (a test without an assertion), prefer-web-first-assertions, no-conditional-in-test and no-networkidle.

import { defineConfig } from 'eslint/config';
import playwright from 'eslint-plugin-playwright';

export default defineConfig([
  {
    files: ['tests/**'],
    extends: [playwright.configs['flat/recommended']],
  },
]);

The Playwright documentation also advises the @typescript-eslint/no-floating-promises rule and a tsc --noEmit check in CI. In the config it is worth blocking a forgotten test.only from being merged: the forbidOnly option, turned on only in CI. All this works as a gate: the mistake does not reach the review.

Example: before → after. This test passed an «it works, merge» review and is always green:

test('checkout', async ({ page }) => {
  await page.goto('/cart');
  await page.getByRole('button', { name: 'Pay' })
    .click({ force: true });
  await page.waitForTimeout(5000);
  // await expect(page.getByText('Paid')).toBeVisible();
});

The assertion is commented out, the pause masks slowness, and force hides that the button is covered. A linter would flag all three (expect-expect, no-wait-for-timeout, no-force-option). After review the test turns red when the payment did not happen:

test('pays for the cart', async ({ page }) => {
  await page.goto('/cart');
  await page.getByRole('button', { name: 'Pay' }).click();
  await expect(page.getByText('Paid')).toBeVisible();
});

Maintainability metrics. The numbers are for seeing a trend, not for setting targets.

  • Share of flaky tests: Playwright marks in the report a test that failed and passed on a retry; the count of such tests per week shows whether instability grows. The --fail-on-flaky-tests flag turns it into a red run where the team is ready to deal with it.
  • Run time (median and p95) and the wait for a result in a PR: a slow suite stops being run.
  • How many tests are switched off with skip or fixme and for how long: a test switched off without a deadline is hidden debt.
  • Cost of change: how many tests have to be fixed after one interface change. A large number signals that locators and steps are not moved into one layer.
  • Time from a red run to the fix: it shows whether the tests have owners.

Limits. A linter does not know whether a test checks the right thing: expect-expect is satisfied by any assertion. Metrics are easy to turn into a target, and then they are «improved» by deleting tests or adding extra retries, which Goodhart’s law describes in general: a measure that becomes a target stops being a measure. Strict rules on an old suite produce thousands of remarks, so they are first turned on for new code or as warnings, and raised to errors gradually. And test review must not be heavier than code review: if it takes longer, the team will bypass it.

Common mistakes.

  • The linter is switched off for the tests folder «so it does not get in the way»: half a year later it holds every violation the linter was meant to catch.
  • Tests are reviewed only for style, not for whether they can fail.
  • «Number of tests» or «coverage» is used as a target: tests without assertions appear.
  • A flaky test is covered with retries and forgotten: the run is green while instability piles up.

Check yourself

The linter is on, the expect-expect rule gives no remarks, and yet the test never fails. How is that possible and what do you do?

Answer

The rule checks only that an assertion exists, not what it means: a test can compare a value with itself or check that an element exists when its text should be checked. Only review catches this: temporarily break the behaviour and see whether the test turns red. A linter removes mechanical mistakes, and the meaningful ones stay with a person.

The team wants the share of flaky tests below 2%. What can go wrong if this becomes a plan?

Answer

The number can be «met» without stability: delete the unstable tests, add more retries or stop marking them as flaky. So the number is used as a trend and a reason to look into specific tests, and the target is stability and reaction time.

In an interview. Junior: A test is code, so it is reviewed, linted and maintained too: a test without an assertion or with a fixed pause does not pass review. Middle/Senior: Machine rules (eslint-plugin-playwright, no-floating-promises, forbidOnly in CI) catch mechanical mistakes, and review is left for meaning: can the test fail. I measure the state of the suite as a trend: share of flaky tests, run time, switched-off tests, cost of change; I do not make these numbers a plan, because then they are «met» by deleting tests.