Reputation: 1
I currently have to 2FA into an application to test it. I set up my playwright test project with the new standard of creating a global-setup.ts
and a setup
project that is marked as a dependency for my other projects in my playwright.config.ts
file. The global-setup.ts
handles my 2FA authentication, logging in, and generates a storageState
into an auth.json
file.
My issue is that when I run my tests npx playwright test --headed --project=chromium
, it is going to trigger that setup
dependency first and then execute my tests, but if the authentication is stored in the auth.json
and the authenticated session last quite a while, is there a simple solution to have my project look to see if the authentication is still valid in auth.json
and if not then it triggers the setup
dependency to run before the rest of my tests.
it is probably super simple, I am just not seeing the approach. Any help is appreciated.
this question came up when I ran npx playwright codegen --load-storage=auth.json
to record a test I was wanting to create. Is there a reason to authenticate every time I run a new test file if it is stored for lets say a few hours?
Upvotes: 0
Views: 597
Reputation: 136
Since the playwright.config.ts
is typescript, you can compose the config at runtime, which I will show below. I don't think it is usually the best practice to modify configuration at runtime, but in this case I think it is reasonable. This is the first approach I thought of in order to skip the setup if your auth.json file exists from a previous run:
import { type PlaywrightTestConfig, Project, devices } from '@playwright/test'
import fs from 'fs'
const storageStatePath = 'playwright/.auth/user.json'
const isSetupNeeded = !isAuthenticationCached()
function isAuthenticationCached() {
// you can add more sophisticated checks here to see if user.json is valid and hasn't expired
return fs.existsSync(storageStatePath)
}
const setupProject: Project = {
name: 'setup',
testMatch: '**/*.setup.ts',
}
const projects: Project[] = [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState: storageStatePath,
},
dependencies: isSetupNeeded ? [setupProject.name] : [],
},
]
if (isSetupNeeded) {
projects.push(setupProject)
}
const config: PlaywrightTestConfig = {
testDir: 'tests',
testMatch: '**/*.test.ts',
use: {
baseURL: 'https://localhost:3123',
},
projects,
}
export default config
This is a modified version of the basic suggested config and setup script in the v1.50 docs [gh permalink]. The modification is to check if the auth.json file exists, and if so, it doesn't run the setup dependency. This approach won't be as nice if you have lots of projects though. Perhaps there is a better way to do this through https://playwright.dev/docs/test-parameterize#parameterized-projects [gh permalink].
Upvotes: 0