HTTP-тестирование узла Mocha - зависание сокета

Здесь аккуратный & amp; оптимизированная реализация функции chunk(). Предполагая размер блока по умолчанию 10.

var chunk = function(list, chunkSize) {
  if (!list.length) {
    return [];
  }
  if (typeof chunkSize === undefined) {
    chunkSize = 10;
  }

  var i, j, t, chunks = [];
  for (i = 0, j = list.length; i < j; i += chunkSize) {
    t = list.slice(i, i + chunkSize);
    chunks.push(t);
  }

  return chunks;
};

//calling function
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var chunks = chunk(list);
-1
задан Jonas Grønbek 6 March 2019 в 22:17
поделиться

2 ответа

Вам нужно позвонить done после завершения асинхронной операции, в настоящее время вы звоните done до того, как у http-сервера появится возможность запуска, и вы никогда не звоните завершено при закрытии http-сервера. Вы можете просто передать done всем обработчикам асинхронного обратного вызова.

before("starting the server..", function (done) {
    httpServer = app.listen(PORT, done) // <- here
})

describe("testing the add endpoint", function () {
    console.log("testing the API now!")
    it("add endpoints result should evaluate to 10", function (done) {
        fetch(`${BASE_URL}add/5/5`)
            .then(response => {
                expect(response.result).to.be(10)
            })
            .then(done) // <- here
            .catch(done) // <- here
    })
})
after("shutting down the server..", function (done) {
    httpServer.close(done) // <- here
})

Как вы можете видеть здесь, я НЕ прикрепил оператор then к функции it.

fetch(`${BASE_URL}add/5/5`).then(response => expect(response.result).to.be(10)).then(done).catch(done)

Если это не решит вашу проблему, то, скорее всего, есть проблема с маршрутом для /add/5/5.

0
ответ дан Jake Holzinger 6 March 2019 в 22:17
поделиться

Вы должны позвонить done() в ваших тестах, в обратном вызове, когда тест закончен. Функция done передается обратному вызову, который вы используете в блоке it. Также вы должны всегда следить за своими ошибками https://mochajs.org/#asynchronous-code

const expect = require("chai").expect
const PORT = require("../server").PORT
const app = require("../server").app
const fetch = require("node-fetch")

const BASE_URL = `https://localhost:${PORT}/api/calc/`
let httpServer;
describe("testing endpoints for calculator Rest API", function () {

    before("starting the server..", function(done) {
        httpServer = app.listen(PORT)
        console.log("server is started")
        done()
    })

     describe("testing the add endpoint", function(){
         console.log("testing the API now!")
         it("add endpoints result should evaluate to 10", function(done){
            fetch(`${BASE_URL}add/5/5`)
            .then(response => {
              expect(response.result).to.be(10)
              done();
            }).catch(e => done(e)) // or just .catch(done)
         })
     })
     after("shutting down the server..", function(){
        httpServer.close()  
     })

})
0
ответ дан djheru 6 March 2019 в 22:17
поделиться
Другие вопросы по тегам:

Похожие вопросы: