Search code examples
node.jsmultipartform-dataplaywrightform-data

Assert FormData in multipart/form-data request in Playwright


I try to test my POST multipart/form-data request using Playwright. I wait for the request to be made, get postData() and try to assert with FormData.

  const requestPromise = page.waitForRequest('**/endpoint')
  await helpers.clickButtonByName('Submit')

  const formData = new FormData()
  formData.append('test', 'something')
  expect((await requestPromise).postData()).toEqual(formData)

I get the error, like:

Error: expect(received).toEqual(expected) // deep equality

Expected: {Symbol(state): [{"name": "test", "value": "something"}]}
Received: "------WebKitFormBoundaryQWipcI3dAh3FVlJW·
Content-Disposition: form-data; name=\"test\"···
something·
------WebKitFormBoundaryQWipcI3dAh3FVlJW--·
"

I want to test that I send a valid payload in the request. How could I do that? Thanks


Solution

  • Playwright is not parsing multipart/form-data posts (it does parse application/x-www-form-urlencoded). I think the most productive way is to perform a contains. Something like this:

    const postData = (await requestPromise).postData();
    for (const key in yourFormDataAsAnObject) {
      if (obj.hasOwnProperty(key)) {
        expect(postData).toContain(`${key}="${obj[key]}"`);
      }
    }
    

    I bet you're expecting a better answer, but this is what I can think of.