Search code examples
playwrightplaywright-typescript

Unable to utilized the value of an index loop inside a test in Playwright


I have a scenario where I would like to have my test cases inside a loop and handle some pre and post test events by using the beforeEach and afterEach while utilizing the index loop value, but encountered a different outcome.

Sample Code

let index: number;
test.describe('Inside a loop test', async () => {
    test.beforeEach(async() => {
        console.log('Before each #' + index);
    });
    for (index = 0; index <= 5; index++) {
        test('Test #' + index, async({}, testInfo) =>{
            console.log('Test name: ' + testInfo.title);
            console.log('Test #' + index);
        });
    }
    test.afterEach(async() => {
        console.log('After each #' + index);
    });
});

On the sample code above, I'm trying to use the index value inside my test, but is always returning only the last possible value, which is 6. The index value in the test title is correct though.

Output

Running 6 tests using 1 worker

Before each #6
Test name: Test #0
Test #6
After each #6

Before each #6
Test name: Test #1
Test #6
After each #6

Before each #6
Test name: Test #2
Test #6
After each #6

Before each #6
Test name: Test #3
Test #6
After each #6

Before each #6
Test name: Test #4
Test #6
After each #6

Before each #6
Test name: Test #5
Test #6
After each #6
  6 passed (658ms)

I declared index in the outer level thinking that it will also help the beforeEach and afterEach, but, unfortunately, only the last value of the index is being considered.

Am I missing something on the Parameterize tests of Playwright?


Solution

  • Put the loop outside the entire describe block and it will run as expected:

    for (let index = 0; index <= 5; index++) {
      test.describe("Inside a loop test", async () => {
        test.beforeEach(async () => {
          console.log("Before each #" + index);
        });
        test("Test #" + index, async ({}, testInfo) => {
          console.log("Test name: " + testInfo.title);
          console.log("Test #" + index);
        });
        test.afterEach(async () => {
          console.log("After each #" + index);
        });
      });
    }
    

    Output:

    Before each #0
    Test name: Test #0
    Test #0
    After each #0
    
    Before each #1
    Test name: Test #1
    Test #1
    After each #1
    
    Before each #2
    Test name: Test #2
    Test #2
    After each #2
    
    Before each #3
    Test name: Test #3
    Test #3
    After each #3
    
    Before each #4
    Test name: Test #4
    Test #4
    After each #4
    
    Before each #5
    Test name: Test #5
    Test #5
    After each #5
    

    The reason for this is in JS the foor loop does not wait for the async function to finish. In other words: by the time the async function starts executing, the for loop has already completed all its iterations, and the index value has reached its final value.