Search code examples
node.jsresttestingsupertest

POST with multipart/form-data using node.js supertest


I was trying to use the Node.js supertest to test some REST API.

request(app)
      .post("/products")
      .set(
        "Authorization",
        "Bearer my jwt token here"
      )
      .set("Content-Type", "multipart/form-data")
      .field("name", "Tomato")
      .field("userId", "5d921d306e96d70a28989127")
      .attach(
        "productImage",
        "D:/NodeJS/node-rest-shop/uploads/1558612339690managing-redis.jpg"
      )
      .expect(201)
      .then(res => {
        const body = res.body;
        expect(body).to.contain.property("message");
        expect(body).to.contain.property("productId");
        expect(body).to.contain.property("date");
        expect(body).to.contain.property("user");
        expect(body).to.contain.property("request");
        done();
      })
      .catch(err => done(err));

.field("userId", userId)

Is there any way to set the value of userId as a variable without setting a hardcoded string value? It is a MongoDB object id.

When I'm using value as a variable this error occurred.

TypeError: source.on is not a function
    at Function.DelayedStream.create (node_modules\delayed-stream\lib\delayed_stream.js:33:10)
    at FormData.CombinedStream.append (node_modules\combined-stream\lib\combined_stream.js:45:37)
    at FormData.append (node_modules\form-data\lib\form_data.js:74:3)
    at Test.RequestBase.field (node_modules\superagent\lib\request-base.js:406:23)
    at Context.done (test\api\product\product.js:77:8)

Solution

  • I can interpret this as 2 different ways, so I'll just answer both:

    Can the value be specified as a non-string, e.g. a number.

    multipart/form-data doesn't really have any sort of typing. Everything will be interpreted as a string usually. Your controller will need to do any conversion.

    Can I use a variable in place of a hardcoded string.

    Yes, you can.

    Instead of:

    .field("userId", "5d921d306e96d70a28989127")
    

    You can just use:

    .field("userId", userId)
    

    As long as you defined a userId variable earlier