NodeJS 开始摩卡测试前,确保Express应用程序正在运行

irtuqstp  于 2022-12-26  发布在  Node.js
关注(0)|答案(2)|浏览(142)

我使用express和node.js为couchbase数据库构建了一个API。我的问题是,当我运行测试时,有些测试失败了,因为服务器没有完全运行。我在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年的,所以我想也许语法已经被弃用了。我想知道是否有人可以帮助我指出正确的方向?

lyfkaqu1

lyfkaqu11#

您可以添加以下条件,详细信息请参见“访问主模块”。

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
}

例如
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)
11dmarpk

11dmarpk2#

嗨,世界!我的小解决方案是:
检查这个:所有都取决于您的测试标记...例如,我正在使用Mocha和ChaiAssert库。

const express = require('express');
const request = require("request");
const http    = require("http");
const expect  = require("chai").expect;
require('dotenv').config();

describe('Server', function() {
  const { PORT } = process.env;
  const app = express();
  before((done) => {
    http.Server = app.listen(PORT, () => {
      console.log(`Listening Node.js server on port: ${PORT}`);
      done();
    });
  });
  it('should return 404 response code status', () => {
    const url = `http://localhost:${PORT}/api/v1/yourPath`;
    return request(url, (err, response, body) => {
      /* Note this result 'cause I don't have any get('/')
      controller o function to return another code status
      */
      expect(response.statusCode).to.equal(404);
    });
  })
});

相关问题