使用node.js超级测试对multipart / form-data进行POST

时间:2019-10-19 18:38:18

标签: node.js rest testing supertest

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

2 个答案:

答案 0 :(得分:0)

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

  

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

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

  

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

是的,可以。

代替:

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

您可以使用:

.field("userId", userId)

只要您之前定义了userId变量

答案 1 :(得分:0)

userId是new mongoose.Types.ObjectId()。因此,它不返回字符串,而是返回一个对象。您需要将其转换为字符串。 我们可以使用它。 .field("userId", String(userId))