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

Patterns

Strategy

Strategy: varying behaviour behind a shared interface

Strategy moves varying behaviour behind a shared contract, so the caller does not know which implementation runs. It has three roles: the contract, the implementations and the context that picks one at run time. In tests that is, for example, login through the UI, the API or SSO. Implementations must give the same postcondition, otherwise they cannot be swapped, and a bare switch is not yet Strategy.

Patterns · Strategy

Login through the UI, the API or SSO. How not to breed ifs in every test?

A framework has a helper login(page, user, mode) with three branches: the form, the API, SSO. At first it is one if. Then a fourth method is added and the branches spread over helpers and fixtures, and every place knows about all the methods. Strategy solves exactly this: the varying behaviour is moved behind a shared interface, and the caller stops knowing which implementation runs.

How it works and why. Strategy defines a family of interchangeable algorithms behind one contract, and the implementation is chosen at run time. There are three roles: the contract (interface), the implementations, and the context that picks and calls one of them. The goal is to separate “what is needed” (“log me in”) from “how to do it”. So the test does not change when a new implementation appears (the Open/Closed principle).

In a test framework typical examples are login methods (UI, API, SSO), payment methods, data generation for different regions, environment drivers (local or in Docker).

The three roles of Strategy

The test or a fixtureasks “log in”, does not know howLoginStrategythe contract: after login the page is authenticatedUiLogin · ApiLogin · SsoLogininterchangeable implementations
Figure 1. The test depends on the contract. The implementation is plugged in from outside.

Example: before and after. Before: one helper knows about all the methods.

export async function login(page: Page, user: User, mode: string) {
  if (mode === 'ui') {
    // open the form, fill, press
  } else if (mode === 'api') {
    // POST /api/login, go to the dashboard
  } else if (mode === 'sso') {
    // redirect to the IdP, the provider form, return
  }
}

After: a contract and two implementations. Four places matter.

interface LoginStrategy {
1  login(page: Page, user: User): Promise<void>;
}

class UiLogin implements LoginStrategy {
  async login(page: Page, user: User) {
    await page.goto('/login');
    await page.getByLabel('Email').fill(user.email);
    await page.getByLabel('Password').fill(user.password);
    await page.getByRole('button', { name: 'Sign in' }).click();
2    await page.waitForURL('/dashboard');
  }
}

class ApiLogin implements LoginStrategy {
  async login(page: Page, user: User) {
3    const res = await page.request.post('/api/login', { data: user });
    expect(res.ok()).toBeTruthy();
4    await page.goto('/dashboard');
  }
}
  1. The contract describes only what is shared: take a page and a user, make the session active.
  2. The end state of the UI variant: the user is on /dashboard.
  3. page.request shares cookies with the page's context, so after an API login the page is already authenticated. Only for a cookie session.
  4. The same end state as the UI variant. The implementations give the same guarantees, so they can be swapped.

In TypeScript a class is not required: a strategy can be a plain function and the choice is a dictionary lookup. That is shorter, and the compiler checks that the keys are complete:

// in TypeScript a strategy can also be a plain function
type Login = (page: Page, user: User) => Promise<void>;

const logins: Record<'ui' | 'api', Login> = {
  ui: async (page, user) => {
    await page.goto('/login');
    // ...
  },
  api: async (page, user) => {
    await page.request.post('/api/login', { data: user });
    await page.goto('/dashboard');
  },
};

Limits and alternatives. The contract should hold only what is truly shared. If ApiLogin cannot do what UiLogin can (say, show a form error), that method does not belong in the contract. The implementations must give the same postcondition: that is the Liskov substitution principle, and it is why both classes above have the same end state. Without it, swapping the implementation changes the test result.

switch versus a contract

Wrong

A switch in every place

A new login method means editing ten files and the risk of missing one.

Right

A contract and implementations

A new method is a new class. Tests and existing strategies do not change.

Figure 2. Strategy wins when there are many methods or more get added. For two fixed variants it is excessive (next lesson).

Common mistakes.

  • Calling any switch a Strategy: the pattern is about polymorphism, that is different implementations of one contract that are swapped independently.
  • A contract bloated with the methods of one implementation: the others have to throw “not supported”, and substitution breaks.
  • Implementations with different postconditions: ApiLogin leaves the page on about:blank and UiLogin on the dashboard, and the test works with only one.
  • The choice of implementation scattered over tests: the context should pick the strategy in one place, for example in a fixture.
  • An API login for an app that keeps the token in localStorage without carrying the token over: the page opens logged out.

Check yourself

ApiLogin ran without errors but then the test lands on /login. Name two plausible causes.

Answer

First: the session is in localStorage or sessionStorage, and page.request carries only cookies. Second: the POST went to another origin or baseURL, so the cookie was set for the wrong domain. Also check res.ok() so that a 401 does not pass unnoticed.

How does a two-class Strategy differ from a login function with if (mode === 'ui') … else …?

Answer

A new method is added as a new class without changing the calling code and the existing implementations. Each implementation can be tested and replaced separately. The function with if forces editing the same place every time and grows into a god helper.

In an interview. Junior: I use Strategy when there are several interchangeable ways to do the same thing, for example login through the UI or the API. The test works with the interface and the implementation is chosen separately. Middle/Senior: The point of Strategy is not a switch but a contract with the same postcondition: after login the session is active whatever the implementation. I make the choice in one place, usually a fixture, and for simple cases I use functions in a dictionary instead of classes.

Fixture options as Strategy and when the pattern is unnecessary

In Playwright, Strategy is implemented with an option fixture: a regular fixture with the { option: true } flag and a default value. The value is set in the config, a project or test.use, and another fixture picks the implementation from it, so the test knows nothing about the choice. With two variants and no new ones expected, a plain if is enough, and browsers and devices are covered by projects.

Patterns · Strategy

The same set of tests must run with a UI login and an API login. Without copying files.

In the previous lesson the context picked the strategy: someone has to create new UiLogin() or new ApiLogin(). Playwright Test has a ready mechanism for this: option fixtures. The value is set in the config, in a file or in a describe, and a fixture chooses the implementation by it. The test knows nothing about it.

How it works and why. An option fixture is a regular fixture with the flag { option: true } and a default value: loginMode: ['api', { option: true }]. The flag allows setting it in the use of the config and projects: Playwright rejects a regular fixture there. Other fixtures depend on the option like on any dependency, so loggedIn receives loginMode and plugs in the right strategy. This is a combination of Strategy and Dependency Injection: the choice is moved out of code into configuration.

The priority order is simple: test.use in a file or describe wins over the project use, and that wins over the default. So one set of tests can run twice in different projects, and a single describe can be pinned to the needed mode.

Who wins

1. The default valueloginMode: ['api', { option: true }]2. The project use in the configprojects: [{ use: { loginMode: 'ui' } }]3. test.use in a file or describetest.use({ loginMode: 'api' })
Figure 1. The closer to the test, the stronger the override.

Example. An option, a dictionary of strategies and a fixture. UiLogin and ApiLogin are from the previous lesson. Four places:

type LoginMode = 'ui' | 'api';
type Opts = { loginMode: LoginMode };

1const strategies: Record<LoginMode, LoginStrategy> = {
  ui: new UiLogin(),
  api: new ApiLogin(),
};

export const test = base.extend<Opts & { loggedIn: void }>({
2  loginMode: ['api', { option: true }],
  loggedIn: async ({ page, loginMode }, use) => {
3    await strategies[loginMode].login(page, defaultUser);
4    await use();
  },
});
  1. A dictionary by a string key: a new value without a matching key will not compile (Record requires all the keys).
  2. An option with a default: tests that specify nothing log in through the API.
  3. The fixture depends on the option and gets the strategy from the dictionary, no if in tests.
  4. await use() without a value: the fixture only prepares state, hence the void type.

The option value is set in the config (then defineConfig takes a generic with the options type) or locally:

// config: one set of tests, two runs
export default defineConfig<Opts>({
  projects: [
    { name: 'api-login', use: { loginMode: 'api' } },
    { name: 'ui-login', use: { loginMode: 'ui' } },
  ],
});

// a file: this describe always goes through the form
test.describe('login form', () => {
  test.use({ loginMode: 'ui' });

  test('shows the dashboard', async ({ page, loggedIn }) => {
    await expect(page).toHaveURL('/dashboard');
  });
});

The option is passed as a string key, not a class instance: the key is visible in the config and the report, and the class is created by the fixture. The test stays the same in both projects, so one scenario is checked with two authorisation methods.

Limits and alternatives. Strategy is not always needed. If there are two variants and no more are expected, a plain if in the fixture is more honest than an interface and three classes. If the difference is one parameter (say, a URL), pass the parameter. For different browsers and devices do not write your own strategy: projects and devices of Playwright already do that.

When the pattern pays off

Two variants

A plain if

Two variants and no more coming: three classes and an interface will not pay off.

A family

Strategy

Three or more methods, each with its own logic, and the list grows.

Figure 2. Both are legitimate: the number of methods and whether the list grows decides.

Common mistakes.

  • Forgetting { option: true }: the value cannot be set in the config or project use, and Playwright stops the run with “cannot be overridden in the configuration "use" section”. test.use in a file still works, so the mistake shows up only in the config.
  • Adding a strategy but not adding its key to the dictionary: Record catches this at compile time while if / else does not, and the test silently takes the default branch.
  • A mode taken from an environment variable without a check (loginMode: process.env.LOGIN_MODE as LoginMode: the cast silences the compiler): if CI does not set the variable, undefined resets the option to its default, and the run silently logs in through the API although it was meant to use the UI.
  • A test that checks the login form itself depends on the option: pin it with test.use({ loginMode: 'ui' }).
  • An option instead of a fixture for data that changes inside a test: an option is about configuration, not about state.

Check yourself

The project sets loginMode: 'ui' and a describe in the file calls test.use({ loginMode: 'api' }). Which mode do the tests in that describe get?

Answer

'api'. test.use in a file or describe has a higher priority than the project use, and that is higher than the default.

The team wants to add a third mode 'sso'. What changes in the tests and what in the framework code?

Answer

Nothing in the tests. In the framework: an SsoLogin class with the same contract, the value 'sso' in LoginMode and a key in the strategies dictionary. The compiler will say if the key is missing. That is Open/Closed.

In an interview. Junior: In Playwright I implement Strategy with an option fixture: the value comes from the config or test.use, and the fixture picks the implementation. If there are two variants and no more will come, I use a plain if. Middle/Senior: The option carries a key, and the strategy instances are created by the fixture from a Record dictionary, so a new value without an implementation does not compile. Priority: test.use is above the project use, and that lets me run one set of tests in different modes without duplication. For browsers and devices I write no strategies: projects exist for that.