typescriptplaywrightplaywright-testtestcontext

How to pass testcontext from beforeAll to other tests?


I using Playwright with TypeScript. In one of my test suites I'm using beforeAll method. The tests failed and after some digging it turn out that the testContext in the beforeAll method is Not the same testContext in my tests.

Please note: all my tests have to get testContext as parameter, I can not change the code to get page or browser.

test.beforeAll(async ({ testContext }) => {        
        const authApi = await testContext.getApi(AuthApi)
        const res = await authApi.login(
            configProvider.loginEmail,
            configProvider.loginPassword
        )       
        homePage = await testContext.getPage(HomePage, {
            shouldNavigate: true,
        })
    })

 test('Test1 - create', async ({ testContext }) => {
    
        // here I need to same testContext as If I used beforeEach and not beforeAll
    })

How can I solve this?


Solution

  • You can fix it but setting the scope of the fixture to worker. See docs.

    Fixture

    import { test as base, expect } from '@playwright/test';
    
    // Define the types for the fixtures
    type MyFixtures = {
      sharedTestContext: any;
    };
    
    class Incrementer {
      private value: number;
    
      constructor() {
        this.value = 0;
      }
    
      get() {
        this.value += 1;
        return this.value;
      }
    }
    
    
    const test = base.extend<MyFixtures>({
      sharedTestContext: [async ({}, use) => {
        const testContext = new Incrementer();
        await use(testContext);
      }, { scope: 'worker' }],
    });
    
    export { test, expect };
    

    Test

    import { test } from './fixtures';
    
    test.beforeAll(async ({ sharedTestContext }) => {
      // Log the sharedTestContext and homePage in beforeEach to confirm they are the same
      console.log(sharedTestContext.get());
    });
    
    test.beforeEach(async ({ sharedTestContext }) => {
      // Log the sharedTestContext and homePage in beforeEach to confirm they are the same
      console.log(sharedTestContext.get());
    });
    
    test('Test1 - create', async ({ sharedTestContext }) => {
      // Use the shared testContext from the fixture
      console.log(sharedTestContext.get());
    });
    

    Output

    ➜  testFixtureQuestion npx playwright test
    
    Running 1 test using 1 worker
    [chromium] › example.spec.ts:8:5 › Test1 - create
    1
    2
    3
      1 passed (354ms)