繁体   English   中英

使用Chai(Node.js)发布方法

[英]Post Method with Chai (Node.js)

我在通过单元测试时遇到了麻烦,我认为这是因为它使用的是错误的数据类型。 我的路线:

let upload = multer({
  storage: storage
});

router.route('/')
    .post(upload.any('image'), function (req, res, next) {
        let memory = new Memory();
        if (req.files.length === 0) {
          Object.assign(memory, req.body);
        } else {
          Object.assign(memory, req.body, {'image': req.file.secure_url});
        }

        memory.save(function (err) {
            if (err) {
                return res.send(err);
            }
            res.json({message: 'Memory Created', memory});
        });
    })

如您所见,我的路线使用了multer ,该multer接受form-data作为输入。 但是,在我的Chai test

it('it should not post an item without a location field', (done) => {
      let formData = new FormData();
      formData.append('description', "First time we met");
      formData.append('image','n/a');

        chai.request(server)
            .post('/api/memory')
            .set('Accept', 'application/form-data')
            .send(formData)
            .end((err, res) => {
                res.should.have.status(200);
                res.body.should.be.a('object');
                res.body.should.have.property('errors');
                res.body.errors.should.have.property('location');
                res.body.errors.location.should.have.property('kind').eql('required');
                done();
            });

我正在使用Chai的send方法,但此测试只是冻结,没有任何响应。 因此,我尝试使用postman ,如果我使用x-www-form-urlencoded发送数据,则会感到发麻,但是如果我使用form-data发送form-data则效果会很好。 所以我怀疑我正在使用Chai在x-www-form-urlencded发送数据。 我该如何解决? (注意:我尝试使用.set('Accept', 'application/form-data')

只需使用.field()

describe('/POST item', () => {
    it('it should not post an item without a location field', (done) => {
        chai.request(server)
            .post('/api/memory')
            .set('Accept', 'application/form-data')
            .field('description', "First time we met")
            .end((err, res) => {
                res.should.have.status(200);
                res.body.should.be.a('object');
                res.body.should.have.property('errors');
                res.body.errors.should.have.property('location');
                res.body.errors.location.should.have.property('kind').eql('required');
                done();
            });
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM