How to unit test with a file upload in mocha

后端 未结 7 1190
走了就别回头了
走了就别回头了 2020-12-14 15:11

I have an app built on Express.js and I\'d like to test the file upload functionality. I\'m trying to reproduce the object parsed to req.files (when using express.bodyParser

7条回答
  •  独厮守ぢ
    2020-12-14 15:47

    If using request promise you can simply do this, sending formData is built into it:

        var options = {
          method: 'POST',
          uri: base + '/api/image/upload',
          formData: {
            someField: 'someValue',
            anotherField: 'anotherValue',
            file: {
              // path to image
              value: fs.createReadStream('./testImg.png'),
              options: {
                filename: 'testImg.png',
                contentType: 'image/png'
              }
            }
          }
        };
        let resp;
        try {
          resp = await request.post(options);
          body = JSON.parse(resp);
        } catch (e) {
          console.log(e);
          resp = e.response;
          code = resp.statusCode;
          body = JSON.parse(resp.body);
        }
        // access what is returned here, check what needs to be
        assert.equal(code, 200, 'Status: ' + code + ': ' + body.error);
        assert.equal(body.success, true);
        assert.exists(body.image);
    

提交回复
热议问题