Search code examples
javascriptplaywright

Playwright - sharing state between tests


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.


Solution

  • 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)
      })
    });