【问题标题】:How to access response body correctly when using Playwright?使用 Playwright 时如何正确访问响应正文?
【发布时间】:2022-07-25 10:22:00
【问题描述】:

我是 Playwright 和 js 的新手,所以我有点迷路了。我希望能够发送请求,然后检查状态、响应内容、标头等。

我以为我可以做类似的事情

  test('blah', async ({ request }) => {
    await request.get('http://localhost:444').then(res => {
      expect(res.status()).toBe(200)
      expect(res.headers()['content-type']).toBe('application/octet-stream')
      expect(res.json()).toContain('foo')
    })
  })

但这不起作用,并且期望将 res.json() 视为“{}”,如果我尝试使用 console.log(res.json()) 将响应打印到控制台,我会返回 Promise { <pending> }

我最终通过使用下面的代码使我的测试正常工作,但对我来说似乎很乱,我不知道为什么我必须这样做?我这样做正确吗?还是我走远了?

test('blah', async ({ request }) => {
    await request.get('http://localhost:4444/')
      .then(res => {
        expect(res.status()).toBe(200)
        return res.json()
      })
      .then(json => {
        expect(JSON.stringify(json)).toContain('foo')
      })
  })

【问题讨论】:

  • 既然已经在使用异步等待,为什么还要使用 then()?
  • 你也要等待json解析return (await res.json())
  • 我基本上是个白痴,需要多学习一点js。这行得通,感谢您的帮助 test('应该允许我添加待办事项', async ({ request }) => { const res = await request.get('localhost:1444'); expect(res.status()) .toBe(200) 期望(JSON.stringify(await newIssue.json())).toContain('foo') })

标签: javascript playwright


【解决方案1】:

我期望的响应包含一个电子邮件和一个令牌字段(请参阅下面的 Postman 捕获),并且我能够通过断言响应的正文电子邮件字段来验证它是否正常工作。

这对我有用

const USER = 'andresdev@gmail.com';
const PWD = 'Test@1234';

test('login to API and check if the email returned it correct', async ({ request }) => {

    // make request and get response
    const loginResponse = await request.post('/api/user/login', {
        data: {
            email: USER,
            password: PWD,
        }
    });

    // assert on response OK (HTTP 200)
    await expect(loginResponse.ok()).toBeTruthy();

    // get 'email' value from response's body data
    var responseEmail = await loginResponse.body().then(b =>{ 
    let data = JSON.parse(b.toString()); 
        return data.email;
    });

    // assert on email from response equal to email from request
    await expect(responseEmail).toEqual(USER);
});

postman capture

【讨论】:

    猜你喜欢
    • 2021-08-03
    • 1970-01-01
    • 2017-09-09
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    • 2018-08-20
    • 1970-01-01
    相关资源
    最近更新 更多