skip to Main Content

I’m learning Playwright and JavaScript concurrently so this may be an elementary question – I’m wondering how people would recommend sharing state – variable customerId in this case – between tests.

Example:

test.describe.only('Generate a new customer', () => {
  let customerId
  let baseUrl = process.env.SHOP_URL
  
  test('Create new customer', async ({ request }) => {
    const response = await request.post(baseUrl +    `/shopify/v5/customer`, {})
    
    const responseBody = JSON.parse(await response.text())
    expect(response.status()).toBe(200)
    customerId = responseBody.customerId //need to persist customerId to pass into following test

  })

  test('Update customer details', async ({ request }) => {
     const response = await request.post(baseUrl +    `/shopify/v5/customer/update`, {})
      {
        data: {
          customerId: customerId, //customerId is undefined here
          name: "Fred"
        },
      }
    )
    expect(response.status()).toBe(200)
  })

the customerId is clearly out of scope in the second test. I will probably refactor these to use a library such as Axios eventually because I am using the Playwright tests to generate data – I’m not actually testing the api here. In the meantime I just need customerId to be persisted in subsequent api calls.

2

Answers


  1. That is anti-pattern, tests should be independent especially in playwright where tests run in parallel by default:

    https://playwright.dev/docs/test-parallel

    You can merge those two tests into one test.

    If You still want to go that way I guess You can use fixtures or hooks to make it work, here are examples:

    https://playwright.dev/docs/test-fixtures#without-fixtures

    Login or Signup to reply.
  2. To make your example work you need to run the tests in serial mode, something like this will work:

    test.describe.serial('Generate a new customer', () => {
      let customerId
      let baseUrl = process.env.SHOP_URL
      
      test('Create new customer', async ({ request }) => {
        const response = await request.post(baseUrl +    `/shopify/v5/customer`, {})
        
        const responseBody = JSON.parse(await response.text())
        expect(response.status()).toBe(200)
        customerId = responseBody.customerId //need to persist customerId to pass into following test
    
      })
    
      test('Update customer details', async ({ request }) => {
         const response = await request.post(baseUrl +    `/shopify/v5/customer/update`, {})
          {
            data: {
              customerId: customerId, //customerId is undefined here
              name: "Fred"
            },
          }
        )
        expect(response.status()).toBe(200)
      })
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search