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
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();
},
});
- A dictionary by a string key: a new value without a matching key will not compile (
Recordrequires all the keys). - An option with a default: tests that specify nothing log in through the API.
- The fixture depends on the option and gets the strategy from the dictionary, no
ifin tests. await use()without a value: the fixture only prepares state, hence thevoidtype.
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
A plain if
Two variants and no more coming: three classes and an interface will not pay off.
Strategy
Three or more methods, each with its own logic, and the list grows.
Common mistakes.
- Forgetting
{ option: true }: the value cannot be set in the config or projectuse, and Playwright stops the run with “cannot be overridden in the configuration "use" section”.test.usein a file still works, so the mistake shows up only in the config. - Adding a strategy but not adding its key to the dictionary:
Recordcatches this at compile time whileif / elsedoes 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,undefinedresets 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.
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.