Как создать макет пост-объекта с указанным размером c в Mocha - PullRequest
0 голосов
/ 18 февраля 2020

В моем коде nodejs я создал функцию, которая, если тело запроса превышает 1 МБ (я проверяю размер с помощью req.get ("content-length")), затем делает что-то. Я хотел бы создать тест в mocha для объекта POST с поддельным размером тела запроса в 1 МБ, чтобы проверить, работает ли моя функциональность.

1 Ответ

1 голос
/ 19 февраля 2020

Короткий ответ, вы можете создать специфицированное тело запроса размера c, например:

const buf = Buffer.alloc(1024 * 1024, '.');

Создать тело запроса размера 1 МБ для вашего дела.

Длинный ответ, вот рабочий пример использования express.js веб-фреймворка и supertest тестового фреймворка.

index.ts:

import express from 'express';
import bodyParser from 'body-parser';

function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return '0 Bytes';

  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

function createServer() {
  const app = express();
  const port = 3000;

  app.use(bodyParser.text({ limit: 10 * 1024 * 1024 /** 10MB */ }));
  app.post('/', (req, res) => {
    console.log(JSON.stringify(req.body));
    const contentLength = req.get('content-length');
    console.log('content length: ', formatBytes(contentLength));
    res.sendStatus(200);
  });

  return app.listen(port, () => {
    console.log(`HTTP server is listening to http://localhost:${port}`);
  });
}

export { createServer };

index.test.ts:

import { createServer } from './';
import request from 'supertest';

describe('60286487', () => {
  let server;
  beforeEach(() => {
    server = createServer();
  });
  afterEach((done) => {
    server.close(done);
  });
  it('should pass', (done) => {
    const buf = Buffer.alloc(1024 * 1024, '.');
    request(server)
      .post('/')
      .send(buf.toString())
      .set('Content-Type', 'text/plain')
      .set('Content-Length', buf.byteLength.toString())
      .expect(200, done);
  });
});

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

.........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................."
content length:  1 MB
    ✓ should pass (3877ms)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...