【发布时间】: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