puppeteer-检查有效载荷为FormData的POST请求

时间:2019-05-10 17:19:05

标签: axios puppeteer form-data jest-puppeteer

我在React中有一个看起来像这样的过程:

handleButtonClick() {
  const payload = new FormData();
  payload.append('foo', someFileBlobContent);
  axios.post('/my-api/', payload);
}

单击按钮时,一些数据将被编译为FormData,然后作为POST请求中的有效载荷发送到API。

在我的Jest / Puppeteer测试中,我试图确认该请求包含它应该包含的数据:

page.click('.my-button');

await page.waitForRequest(request => {
  if (request.url().match(/my-api/) && request.method() === 'POST') {
    expect(request.postData()).toBeDefined();
    return true;
  }
});

在这种情况下,request.postData()undefined。 Puppeteer中有什么方法可以检查有效载荷为FormData结构的POST请求的内容吗?

在Chrome中运行该过程时,我可以看到通过Chrome devtools在网络请求中显示的FormData,因此我知道数据已发送,但是我想声明它。

1 个答案:

答案 0 :(得分:1)

我做了一些测试,request.postData()仅对application/x-www-form-urlencoded表单(也称为“常规表单数据”)有用。上传文件后,content-type即为multipart/form-data,并且操纵p的人将无法返回帖子数据。

替代:检查Content-Type标头

由于您无法检查是否已发送过帐数据,因此仍然可以检查该请求是否实际上是multipart/form-data请求。在这种情况下,content-type标头看起来像这样的multipart/form-data; boundary=...,因此您可以像这样检查它:

await page.waitForRequest(request => {
  if (request.url().match(/my-api/) && request.method() === 'POST') {
    const headers = request.headers();
    expect(headers['content-type'].startsWith('multipart/form-data')).toBe(true);
    return true;
  }
});
相关问题