Как отправить тело с формой данных в формате мокко чай - PullRequest
0 голосов
/ 23 марта 2020

Это мой заголовок почтальон:

enter image description here

Это мои данные формы тела в почтальоне:

enter image description here

Я уже пытаюсь вот так

describe('test', function() {
  describe('Get User Data', function() {
    it.only('bla bla bla', function(done) {
      // Send some Form Data
      chai
        .request(app)
        .post('/user/login')
        .send({ username: 'ihdisetiawan', password: 'testing123' })
        .set('Accept', 'application/json')
        .set('x-api-key', '1234567890')
        .end(function(err, res) {
          expect(res.status).to.equal(responseMessageCode.successOk);
          // expect(res.password).to.equal("testing123");
          done();
        });
    });
  });
});

ответ получен 422

Uncaught AssertionError: expected 422 to equal 200
      + expected - actual

      -422
      +200

1 Ответ

0 голосов
/ 30 марта 2020

Вам необходимо использовать промежуточное программное обеспечение multer для обработки полезной нагрузки запроса с типом контента multipart/form-data. Кроме того, в вашем случае обрабатывается только текстовая многочастная форма, вы должны использовать метод .none() multer.

Например,

server.ts:

import express from 'express';
import multer from 'multer';

const app = express();
const port = 3000;
const upload = multer();
app.post('/user/login', upload.none(), (req, res) => {
  console.log('username:', req.body.username);
  console.log('password:', req.body.password);
  console.log('content-type:', req.get('Content-Type'));
  console.log('x-api-key:', req.get('x-api-key'));
  res.sendStatus(200);
});

if (require.main === module) {
  app.listen(port, () => {
    console.log(`HTTP server is listening on http://localhost:${port}`);
  });
}

export { app };

server.test.ts:

import { app } from './server';
import request from 'supertest';
import { expect } from 'chai';

describe('test', () => {
  describe('Get User Data', () => {
    it('bla bla bla', (done) => {
      request(app)
        .post('/user/login')
        .field({
          username: 'ihdisetiawan',
          password: 'testing123',
        })
        .set('x-api-key', '1234567890')
        .end((err, res) => {
          expect(res.status).to.equal(200);
          done();
        });
    });
  });
});

Результаты интеграционных испытаний с отчетом о покрытии:

  test
    Get User Data
username: ihdisetiawan
password: testing123
content-type: multipart/form-data; boundary=--------------------------481112684938590474892724
x-api-key: 1234567890
      ✓ bla bla bla (47ms)


  1 passing (66ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |   86.67 |       50 |      50 |   86.67 |                   
 server.ts |   86.67 |       50 |      50 |   86.67 | 16,17             
-----------|---------|----------|---------|---------|-------------------
...