skip to Main Content

In my testing, I need to simulate sending checkbox form data. In a normal HTML form with checkboxes, if a form box is checked, the corresponding key, value is sent. Consider a form that asks user for their favourite color. The submitted data would look like:

color=red
color=blue
color=green

I believe this is correct.

In express, I logged out the req.body.color and as expected I got an array of [red, green, blue] when sending the request with postman. However, if I try to send the data in supertest, it only gets the last sent key value pair. I have sent the form data in supertest with .type('form').send({color: 'red', color: 'green', color: 'blue'}) however when it hits the server, req.body.color is just [‘blue’]

How can I send multiple key value pairs in supertest with same key but different values which ALL get sent?

2

Answers


  1. You cann’t set same key in a single object. if you will try to set same key in single object then it will override old key value with new one.

    If you want to send multiple value in single key in a object then you can make ‘color’ as a array

    .type('form').send({color: ['red','green','blue']})
    

    If you don’t want to make an array then you can also try formdata

    let formData = new FormData();
    formData.append('color', 'red');
    formData.append('color', 'red2');
    formData.append('color', 'red3');
    for (const pair of formData.entries()) {
      console.log(pair[0], pair[1]);
    }
    
    Output: 
    "color" "red"
    "color" "red2"
    "color" "red3"
    
    Login or Signup to reply.
  2. If you read the documentation under the section POST / PUT requests my guess would be that sending {color: 'red', color: 'green', color: 'blue'} will result in a request with the content-type application/json (even though it reads that type('form') will send using application/x-www-form-urlencoded) or just a misinterpretation of some kind.

    Try doing (like the second last example in the documentation section):

    request.post('/endpoint').type('form')
      .send({ color: 'red' })
      .send({ color: 'green' })
      .send({ color: 'blue' })
      .then(callback, errorCallback)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search