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

Patterns

Facade, Steps and App Actions

Facade and business steps

A Facade in tests is a class of business steps that composes several Page Objects into one action and owns no locators. It removes a repeated click sequence from dozens of tests, and test.step gives the report and trace a readable step name. The facade hides preconditions, not what the test verifies: the assertion stays in the test.

Patterns · Facade

Thirty tests start with the same eight clicks of a transfer. Where should they live?

A test about transfer history first has to make a transfer: open an account, press “Transfer”, fill two fields, confirm. These eight lines repeat in thirty tests. A Page Object already hides the locators, but the sequence across two pages stays in every test. When the confirmation gets one more screen, all thirty need an edit. A Facade removes exactly this repetition: one call instead of a sequence.

How it works and why. A Facade gives a simple interface to a complex subsystem. In tests the subsystem is several Page Objects and API calls, and the facade is a “steps” class with business-language methods: sendMoney, passKyc. It owns no locators: everything about a page stays in its Page Object, and the facade only composes an action from them. So a UI change is fixed in one Page Object, a change of the scenario itself (a new screen appeared) in one facade method, and the tests are not touched.

The second contribution is test.step: it groups actions under one name in the HTML report and the trace. A failure reads as “send 100 from UA001 to UA002”, not as a click on an unknown button.

Where the Facade sits

The testa precondition in one line, expect hereTransferSteps (Facade)one business action = several pagesAccountsPage, TransferPagelocators and page actionsUIthe browser, the app
Figure 1. The Facade only composes an action from pages. The check does not move down: expect stays in the test.

Example: before and after. First, the test without a facade. Seven of eight lines are about the transfer, and only one is about what is checked:

test('history lists a fresh transfer', async ({ page }) => {
  await page.goto('/accounts/UA001');
  await page.getByRole('button', { name: 'Transfer' }).click();
  await page.getByLabel('To').fill('UA002');
  await page.getByLabel('Amount').fill('100');
  await page.getByRole('button', { name: 'Confirm' }).click();
  await page.goto('/history');
  await expect(page.getByRole('row').first()).toContainText('100.00');
});

Now the steps class. Four places matter.

export class TransferSteps {
1  constructor(
    private readonly accounts: AccountsPage,
    private readonly transfer: TransferPage,
  ) {}

  async sendMoney(from: string, to: string, amount: number) {
    return test.step(
2      'send ' + amount + ' from ' + from + ' to ' + to,
      async () => {
        await this.accounts.open(from);
        await this.accounts.clickTransfer();
        await this.transfer.fill(to, amount);
3        return this.transfer.confirm(); // returns the transfer reference
      },
4      { box: true },
    );
  }
}
  1. The facade receives Page Objects in its constructor and does not create them: it is easy to assemble in a fixture.
  2. The step name contains the data, so the report shows which transfer failed.
  3. test.step returns what the callback returned: the transfer reference can be used in the test.
  4. { box: true }: the error points to the sendMoney call line in the test, not to the clicks inside the step.

The facade is plugged in as a fixture (see the lesson on fixtures), and the test shrinks to what it checks:

export const test = base.extend<{ steps: TransferSteps }>({
  steps: async ({ page }, use) => {
    await use(
      new TransferSteps(new AccountsPage(page), new TransferPage(page)),
    );
  },
});

test('history lists a fresh transfer', async ({ page, steps }) => {
  const ref = await steps.sendMoney('UA001', 'UA002', 100);
  await new HistoryPage(page).open();
  await expect(page.getByTestId('row-' + ref)).toContainText('100.00');
});

Limits and alternatives. The main rule: a facade hides preconditions and repeated end-to-end paths, not what the test checks. If a test is about validation of the transfer form, it works with TransferPage directly, because the fields and messages are the subject of the check.

What to hide in a facade

Right

A Facade for a precondition

A test about transfer history calls sendMoney: the transfer is needed but it is not what is checked.

Wrong

A Facade hides the check itself

A limit test calls sendMoneyAndCheckLimit: neither the data nor the expectation is visible in the test body.

Figure 2. What a test only prepares can be hidden. What it checks must stay visible.

If a precondition does not need the UI, it is better done through the API (next lesson): that is faster and more stable than clicking. A UI facade is justified when the path through the interface is part of the scenario or there is no other entry. The Cypress analogue is custom commands, in Selenium it is “step” classes; the idea is the same.

Common mistakes.

  • Layers Test → Steps → Actions → Pages → Components where each one just forwards the call: indirection without abstraction, and the real click is hard to find while debugging.
  • A facade method containing expect for several things at once: when it fails it is unclear what is wrong, and a test about something else suddenly checks the transfer.
  • A facade per page (“AccountsSteps”, “TransferSteps” with one method): that is a Page Object under another name. A facade should combine several pages.
  • One giant steps class for the whole app: it becomes a god object. Cut it by domain: transfers, KYC, cards.
  • A step without test.step: the report and the trace show raw clicks again, and the main benefit of the facade is lost.

Check yourself

A test about amount validation calls steps.sendMoney('UA001', 'UA002', -5) and expects an error. What is wrong?

Answer

The facade assumes the transfer succeeds and hides the fields and messages that are the subject here. The test should work with TransferPage directly: fill, confirm, expect on the error message.

What changes in the report if test.step is removed from sendMoney and the rest is left as is?

Answer

The logic works the same, but the report and the trace show separate clicks and fills instead of the step “send 100 from UA001 to UA002”. The group is gone, so it is harder to see at which stage of the transfer it failed.

In an interview. Junior: A Facade is a steps class that combines several Page Objects into one business action, such as “make a transfer”, and wraps it in test.step for the report. Middle/Senior: A facade in tests is for preconditions and repeated paths, not for the check itself: expect and the data being verified stay visible in the test. I make sure it does not become one more forwarding layer, and where possible I replace UI preconditions with API calls.

App Actions: preconditions without the UI

App Actions means preparing test preconditions bypassing the interface: through the app's internal actions, an API, the database or a saved session. Only what the test verifies goes through the UI. Playwright offers storageState with a setup project, the request fixture and page.route. A few end-to-end UI tests are still needed, otherwise a broken login form goes unnoticed.

Patterns · App Actions

Every test logs in through the form and the run takes twenty minutes. What can be skipped?

In a suite of two hundred tests each one starts with the login form: a navigation, two fields, a button, waiting for the redirect. That is a few seconds times two hundred, plus two hundred chances to fail on a form the test has nothing to do with. A transfer test should not depend on whether the Email field works. App Actions is the approach where preconditions are prepared bypassing the interface.

How it works and why. The term came from the Cypress blog (2019): drive the application directly through its internal model that it exposes to tests, for example an object on window, instead of clicking the UI. Today it names a wider idea: prepare state by the cheapest reliable path, that is through the API, the DB or a saved session. The principle is simple: only what the test verifies goes through the UI. Everything else is a precondition, and the less it depends on the interface, the faster and more stable the test.

Playwright has three mechanisms for this:

  • storageState + a setup project. Log in once and save cookies and localStorage to a file. Other projects plug it in with use: { storageState }.
  • The request fixture. Creates data through the API before the test (an account, a user), and a fixture removes it afterwards.
  • page.route. Replaces backend responses when a specific state is needed that is hard to create (for example, a server error).

What to prepare where

UI login in every testa form, a redirect, N times per runAPI login once in setupcookies to a file, tests start logged inThe login test itselfthe form and messages: UI belongs here
Figure 1. The UI path is kept for what the test checks, the rest is prepared cheaper.

Example: before and after. Before: a login in beforeEach of every file.

test.beforeEach(async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill('qa@example.com');
  await page.getByLabel('Password').fill(process.env.QA_PASS!);
  await page.getByRole('button', { name: 'Sign in' }).click();
  await page.waitForURL('/dashboard');
});

After: a separate setup file logs in through the API once.

// auth.setup.ts
import { test as setup, expect } from '@playwright/test';

setup('authenticate', async ({ request }) => {
  const res = await request.post('/api/login', {
    data: { email: 'qa@example.com', password: process.env.QA_PASS },
  });
  expect(res.ok()).toBeTruthy();
  await request.storageState({ path: '.auth/user.json' });
});

In the config the setup is a project, and the main project depends on it and takes the saved state:

// playwright.config.ts
export default defineConfig({
  use: { baseURL: 'http://localhost:3000' },
  projects: [
    { name: 'setup', testMatch: /.*\.setup\.ts/ },
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'], storageState: '.auth/user.json' },
      dependencies: ['setup'],
    },
  ],
});

The .auth/ folder goes to .gitignore: it holds live sessions. The setup project runs before every run, so the state does not go stale between runs.

Limits and alternatives. The main trap: request.storageState() saves cookies. If the app keeps the token in localStorage, an API login does not carry it over, and the page opens logged out. Then the token from the response is added to the state's origins (code below), or setup logs in through the UI once. Playwright does not save sessionStorage in storageState at all: for it there is only a workaround through addInitScript.

// the token lives in localStorage: cookies are not enough, origins must be added
const { token } = await res.json();
const state = await request.storageState();
state.origins = [
  {
    origin: 'http://localhost:3000',
    localStorage: [{ name: 'token', value: token }],
  },
];
fs.writeFileSync('.auth/user.json', JSON.stringify(state));

Where the UI is needed and where it is not

The subject

A login test

Goes through the form in the UI: that is the check.

A precondition

A transfer test

The login comes from a saved state, the form is not needed.

Figure 2. Both paths are legitimate: the choice depends on what the test checks.

Two more limits. Tests that change the user's data cannot run in parallel on one account: an account per worker is needed (see the lesson on worker fixtures). And a few end-to-end tests must remain that go through the key path fully via the UI: otherwise a broken login form goes unnoticed, because all other tests bypass it.

Common mistakes.

  • A UI login in every test that is not about login: slow, and the form becomes the cause of unrelated failures.
  • One account for all workers while tests change its data: races and flakes that are hard to reproduce.
  • A committed .auth/user.json: live cookies end up in the repository.
  • The token is in localStorage but only cookies are saved: the test opens logged out and fails on the first click.
  • No UI test for the login itself: the bypass everywhere hides a broken form.

Check yourself

The API login in setup passed (200) but tests open /login. The app stores the token in localStorage. Why and what to do?

Answer

request.storageState() saves cookies and localStorage stays empty, so the page does not see the token. Add the token from the response to the state's origins[].localStorage, or log in through the UI once in setup.

Should the test of the login form itself use storageState?

Answer

No. The form and its error messages are the subject there, so the test should start logged out (use: { storageState: { cookies: [], origins: [] } }) and go through the UI.

In an interview. Junior: I prepare preconditions through the API and a saved state, not through the UI: it is faster and more stable. I go through the UI only for what the test checks. Middle/Senior: I log in in a setup project and save storageState. I remember it holds cookies and localStorage but not sessionStorage, so a token in localStorage has to be added. I split user data per worker and keep a few end-to-end UI tests so a broken form is not missed.