Skip to content

Instantly share code, notes, and snippets.

@oofnivek
Last active June 16, 2025 14:51
Show Gist options
  • Select an option

  • Save oofnivek/af42d3954882c06c8f4fb7bb811377ef to your computer and use it in GitHub Desktop.

Select an option

Save oofnivek/af42d3954882c06c8f4fb7bb811377ef to your computer and use it in GitHub Desktop.
// global-setup.ts (or .js)
import { request, expect } from '@playwright/test';
import * as fs from 'fs';
import * as path from 'path';
// Credentials for Basic Authentication
const LOGIN_EMAIL = '[email protected]';
const LOGIN_PASSWORD = 'changeme';
async function globalSetup() {
console.log('Running global setup to obtain JWT...');
const reqContext = await request.newContext(); // Create a new request context for the setup
try {
const loginResponse = await reqContext.post(`https://api.escuelajs.co/api/v1/auth/login`, {
data: {
email: LOGIN_EMAIL,
password: LOGIN_PASSWORD,
},
});
expect(loginResponse.status()).toBe(201);
const loginResponseBody = await loginResponse.json();
const access_token = loginResponseBody.access_token;
expect(access_token).toBeTruthy();
console.log('Obtained JWT successfully:', access_token);
// Define the path where the auth state will be saved
const authFile = path.join(__dirname, 'playwright/.auth/user.json');
// Ensure the directory exists
fs.mkdirSync(path.dirname(authFile), { recursive: true });
// Save the access token to a file.
fs.writeFileSync(authFile, JSON.stringify({ access_token }));
} catch (error) {
console.error('Failed to obtain JWT during global setup:', error);
process.exit(1); // Exit with an error code if setup fails
} finally {
await reqContext.dispose(); // Dispose the context
}
}
export default globalSetup;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment