如何使用 Supertest 对文件上传进行单元测试并发送令牌?

问题描述 投票:0回答:3

如何使用发送的令牌来测试文件上传?我返回“0”而不是确认上传。

这是一次失败的测试:

var chai = require('chai');
var expect = chai.expect;
var config = require("../config");  // contains call to supertest and token info

  describe('Upload Endpoint', function (){

    it('Attach photos - should return 200 response & accepted text', function (done){
        this.timeout(15000);
        setTimeout(done, 15000);
        config.api.post('/customer/upload')
              .set('Accept', 'application.json')
              .send({"token": config.token})
              .field('vehicle_vin', "randomVIN")
              .attach('file', '/Users/moi/Desktop/unit_test_extravaganza/hardwork.jpg')

              .end(function(err, res) {
                   expect(res.body.ok).to.equal(true);
                   expect(res.body.result[0].web_link).to.exist;
               done();
           });
    });
});

这是一个工作测试:

describe('Upload Endpoint - FL token ', function (){
   this.timeout(15000);
    it('Press Send w/out attaching photos returns error message', function (done){
    config.api.post('/customer/upload')
      .set('Accept', 'application.json')
      .send({"token": config.token })
      .expect(200)
      .end(function(err, res) {
         expect(res.body.ok).to.equal(false);
         done();
    });
});

如有任何建议,我们将不胜感激!

unit-testing mocha.js endpoint chai supertest
3个回答
27
投票

使用 supertest 4.0.2,我能够

set
令牌和
attach
文件:

import * as request from 'supertest';

return request(server)
  .post('/route')
  .set('Authorization', 'bearer ' + token)
  .attach('name', 'file/path/name.txt');

更好的是,根据 docs,您可以创建一个要附加的 Buffer 对象:

const buffer = Buffer.from('some data');

return request(server)
  .post('/route')
  .set('Authorization', 'bearer ' + token)
  .attach('name', buffer, 'custom_file_name.txt');

4
投票

附加文件时令牌字段似乎被覆盖。我的解决方法是向 URL 查询参数添加令牌:

describe('Upload Endpoint - FL token ', function (){
   this.timeout(15000);
    it('Press Send w/out attaching photos returns error message', function (done){
    config.api.post('/customer/upload/?token='+config.token)
      .attach('file', '/Users/moi/Desktop/unit_test_extravaganza/hardwork.jpg')
      .expect(200)
      .end(function(err, res) {
         expect(res.body.ok).to.equal(false);
         done();
    });
});

您的身份验证中间件必须设置为从 URL 查询参数中提取 JWT。 Passport-JWT 在我的服务器上执行此提取。


3
投票

官方文件规定

当您使用 .field() 或 .attach() 时,您不能使用 .send() 并且不能设置 Content-Type(将为您设置正确的类型)。

所以更换


              .send({"token": config.token})

              .field("token", config.token)

© www.soinside.com 2019 - 2024. All rights reserved.