Search code examples
playwrightplaywright-test

Playwright save storage state only for certain files


I currently have a test pack that has >50 files. 49 of the files will use the same authentication, so I have set up the below inside my playwright config file:

                storageState: 'myauth.json',

This allows me to store the state and use it across all of the tests, the issue becomes where I don't want to use this state in one of my tests. How would one go about this?

I'm aware I could pass the state into 49 of the files and ignore it for the one, but this seems like the wrong idea.


Solution

  • You can use fixtures and as default value set the one you use 49 times. In that case when you are need other auth just overwrite it with keyword "use". It is described in playwright doc. https://playwright.dev/docs/test-fixtures

    import { TodoPage } from './todo-page';  //In your case auth1 auth2
    import { SettingsPage } from './settings-page';
        
    // Declare the types of your fixtures.
    type MyFixtures = {
      todoPage: TodoPage;
      settingsPage: SettingsPage;
    };
        
    // Extend base test by providing "todoPage" and "settingsPage".
    // This new "test" can be used in multiple test files, and each of them will get the fixtures.
    export const test = base.extend<MyFixtures>({
      todoPage: async ({ page }, use) => {
        // Set up the fixture.
        const todoPage = new TodoPage(page);
        await todoPage.goto();
        await todoPage.addToDo('item1');
        await todoPage.addToDo('item2');
        
        // Use the fixture value in the test.
        await use(todoPage);
       
        // Clean up the fixture.
        await todoPage.removeAll();
      },
    
      settingsPage: async ({ page }, use) => {
        await use(new SettingsPage(page));
      },
    });
    

    Default auth use as you you page in your tests. And when you need to overwrite in your specific file spec.ts file just write:

    test.use({ auth: 'reareAuth' });