Search code examples
typescriptplaywrightteardown

How do I get global teardown to work with Playwright?


I've been trying to set up a global teardown for a Playwright, but I can't find any way to get it to run. I've tried following the examples in the docs, but it still doesn't work for some reason. I'm not running a setup, but I don't see how it would effect the running of teardown. In the config, I just use the globalTeardown option to point to the file that I want to run. Here is an example of what I have in the file I'm pointing to;

async function globalTeardown(_config: FullConfig) {
    const browser = await chromium.launch();
    const context = await browser.newContext();
    const page = new CustomPage(await context.newPage());

    try{
        await context.tracing.start({ screenshots: true, snapshots: true });
        cleanUpFunc(page);

        await browser.close();
    } catch (error) {
        context.tracing.stop({ 
            path: './test-results/teardown-trace.zip',
        });
        await browser.close();
        throw("Global setup error:\n" + error);
    }

}

Then in cleanUpFunc, it'd just be some functions that are on the Page object, or CustomPage object that I can't really come up with an example of.

I can't provide specific code, as I am under NDA, but I can try to provide an example, if needed.

Thank you!


Solution

  • No one knows what code you run, but probably you don't await cleanUpFunc.

    // global-teardown.ts
    
    async function globalTeardown() {
      const browser = await chromium.launch();
      const context = await browser.newContext();
      const page = await context.newPage();
    
      try {;
        await context.tracing.start({ screenshots: true, snapshots: true });
        await cleanUpFunc(page);
      } catch (e) {
        console.log(`Error in globalTeardown: ${e}`);
      } finally {
        await browser.close();
      }
    }
    
    export default globalTeardown;
    

    and config

    // playwright.config.ts
    
    const config: PlaywrightTestConfig = {
      globalTeardown: "./global-teardown.ts",
    }