首页 > 解决方案 > 使用 node.js supertest 使用 multipart/form-data POST

问题描述

我试图使用 Node.js supertest 来测试一些 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 )

有没有办法在不设置硬编码字符串值的情况下将userId的值设置为变量?它是一个 MongoDB 对象 ID。

当我使用 value 作为变量时,发生了此错误。

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)

标签: node.jsresttestingsupertest

解决方案


我可以将其解释为两种不同的方式,所以我将同时回答:

可以将值指定为非字符串,例如数字。

multipart/form-data真的没有任何类型的打字。通常,所有内容都将被解释为字符串。您的控制器将需要进行任何转换。

我可以使用变量代替硬编码的字符串吗?

是的你可以。

代替:

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

您可以使用:

.field("userId", userId)

只要你之前定义了一个 userId 变量


推荐阅读