Test API upload file using Playwright when having both multipart and formdata

Playwright request currently does not support having both multipart and formdata. It only supports one type of multipart, formdata, or data alone. So how do we pass the form data along with multipart.

Donald Le
2 min readFeb 23

--

Photo by Austvika

Take this upload file with Postman as an example:

In this API upload file, we’re having form-data with forms for “file”, “data_type”, “gr”. When making API request with Playwright, we must include this form along with mimeType like this:

await request.post(`/api/core/projects/${projectId}/studies`,{
headers:{
'Authorization':`Bearer ${accessToken}`,
'ContentType':'multipart/form-data'
},
multipart:{
file: {
name:file,
mimeType:"application/octet-stream",
buffer: jsonFile,
},
},
form:{
data_type:dataType,
group_study_by_folder:groupStudyByFolder,
filename:file,
name:file,
file:file
}
})

Running this test will cause error:

apiRequestContext.post: Only one of 'data', 'form' or 'multipart' can be specified

To fix this error, we must put the form inside the block of multipart as below:

await request.post(`/api/core/projects/${projectId}/studies`,{
headers:{
'Authorization':`Bearer ${accessToken}`,
'ContentType':'multipart/form-data'
},
multipart:{
...{
data_type:dataType,
group_study_by_folder:groupStudyByFolder,
filename:file,
name:file,
file:file
},
file: {
name:file,
mimeType:"application/octet-stream",
buffer: jsonFile,
},
},
})

The test now will be passed.

Hope it helps~~

PEACE

--

--

Donald Le

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

Recommended from Medium

Lists