Убедитесь, что экспресс-приложение запущено, прежде чем запускать тесты мокко.

Я создал API для базы данных Couchbase, используя Express и node.js. Моя проблема в том, что когда я запускаю свои тесты, некоторые из них терпят неудачу, потому что сервер не полностью запущен. Я нашел решение здесь https://mrvautin.com/ensure-express-app-started-before-tests о том, как решить эту проблему. В статье говорилось, что для решения этой проблемы вам необходимо добавить эмиттер событий в файл вашего сервера, как это

app.listen(app_port, app_host, function () {
    console.log('App has started');
    app.emit("appStarted");
});

а затем добавьте это в свой тестовый файл

before(function (done) {
    app.on("appStarted", function(){
        done();
    });
});

Я пробовал это, вот моя реализация

Файл сервера

app.listen(config['server']['port'], function(){
    app.emit("appStarted");
    logger.info("Listening")
})

Тестовый файл

before(function(done){
    app.on("appStarted", function(){
        done();
    })
});

Я продолжаю получать следующую ошибку

  1) "before all" hook in "{root}":
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
      at listOnTimeout (internal/timers.js:549:17)
      at processTimers (internal/timers.js:492:7)

Статья от 2016 года, поэтому я подумал, что, возможно, синтаксис устарел. Мне было интересно, может ли кто-нибудь помочь указать мне правильное направление?


person Sergei Poliakov    schedule 10.09.2020    source источник


Ответы (1)


Вы можете добавить приведенное ниже условие, дополнительную информацию см. в разделе Доступ к основному модулю.

if (require.main === module) {
     // this module was run directly from the command line as in node xxx.js
} else {
     // this module was not run directly from the command line and probably loaded by something else
}

E.g.

index.ts:

import express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.sendStatus(200);
});

if (require.main === module) {
  app.listen(port, () => {
    console.log('App has started');
  });
}

export { app, port };

index.test.ts:

import { app, port } from './';
import http from 'http';
import request from 'supertest';

describe('63822664', () => {
  let server: http.Server;
  before((done) => {
    server = app.listen(port, () => {
      console.log('App has started');
      done();
    });
  });
  after((done) => {
    server.close(done);
    console.log('App has closed');
  });
  it('should pass', () => {
    return request(server)
      .get('/')
      .expect(200);
  });
});

результат интеграционного теста:

(node:22869) ExperimentalWarning: The fs.promises API is experimental
  63822664
App has started
    ✓ should pass
App has closed


  1 passing (26ms)
person slideshowp2    schedule 22.09.2020