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.

More articles in this chapter