Playwright - 在测试之间共享状态

Ste*_*ike 4 javascript playwright

我正在同时学习 Playwright 和 JavaScript,所以这可能是一个基本问题 - 我想知道人们如何建议customerId在测试之间共享状态 - 在这种情况下是变量。

例子:

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)
  })
Run Code Online (Sandbox Code Playgroud)

customerId显然超出了第二次测试的范围。我最终可能会重构它们以使用 Axios 等库,因为我正在使用 Playwright 测试来生成数据 - 我实际上并没有在这里测试 api。与此同时,我只需要customerId在后续的 api 调用中坚持下去。

Yur*_*sky 5

为了使您的示例正常工作,您需要以串行模式运行测试,如下所示:

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)
  })
});
Run Code Online (Sandbox Code Playgroud)