I am trying to perform some API testing with Playwright. I have what I thought was a neat solution for handling different users, but now I am not so sure. For each user, I have a fixture:
import { APIRequestContext, test as baseTest } from '@playwright/test';
import { apiLogin } from 'apiLogin';
type ApiLoginFixtures = {
Administrator: APIRequestContext;
PowerUser: APIRequestContext;
User: APIRequestContext;
};
export const test = baseTest.extend<ApiLoginFixtures>({
Administrator: async ({}, use) => {
const context = await apiLogin('ADMINISTRATOR');
await use(context);
await context.dispose();
},
PowerUser: async ({}, use) => {
const context = await apiLogin('POWERUSER');
await use(context);
await context.dispose();
},
User: async ({}, use) => {
const context = await apiLogin('USER');
await use(context);
await context.dispose();
},
});
I can then use these contexts in my test, e.g. await PowerUser.get('/some/endpoint');
That's great. However, I would like to write a single test that can be looped over, using all the different user types that I have. It would be great if I could do something like the following (but this does not work)...
// Fixture file
export const test = baseTest.extend<ApiLoginFixtures>({
UserFixture: {} as APIRequestContext,
Administrator: async ({}, use) => {
const context = await apiLogin('ADMINISTRATOR');
await use(context);
await context.dispose();
},
// [...] PowerUser, etc.
});
// Test file
let fixtures: {name: string, theFixture: APIRequestContext}[] = [];
test.beforeAll(async ({ Administrator, PowerUser }) => {
fixtures.push(
{name: 'Administrator', theFixture: Administrator},
{name: 'PowerUser', theFixture: PowerUser},
)
});
for (const {name, theFixture} of fixtures) {
test.describe(`Test suite for some/endpoint`, async () => {
test.use({UserFixture: theFixture});
test(`GET some/endpoint as ${name}`, { tag: '@someTag' }, async ({ UserFixture }) => {
const response = await UserFixture.get('/some/endpoint');
expect(response.status()).toBe(200);
});
});
}
Are there any suggestions, or do I need to start over and rewrite the way I handle users and logins?