首页 > 解决方案 > Ts and jest 测试路线的最佳方式

问题描述

我从开玩笑开始,我正在尝试测试一条路线,但我不知道最好的方法是什么,就像我用 docker 做的那样,我上了 docker 并启动服务器express 但在我的测试中我再次创建它并且我的端口已经在使用中:

● Hello Word Route › should return a json with value: hello word

    listen EADDRINUSE: address already in use :::8080

      50 | 
      51 |   public start(): void {
    > 52 |     this.server = this.express.listen(Number(process.env.APP_PORT) || 8080, () => {

我有以下引导程序来启动我的服务器:

class ApplicationServer implements Server {
  private express: Application;
  private logger: LoggerProvider;
  private server: http.Server
  constructor(logger: LoggerProvider) {
    this.express = express();
    this.logger = logger;
  }

  public getExpress(): Application {
    return this.express
  }

  public getLogger():LoggerProvider {
    return this.logger;
  }

  public getServer():http.Server {
    return this.server;
  }

  public async close(): Promise<void> {
    try {
      this.logger.log(`info`, `closing the http server`, {})
      this.server.close()
      this.logger.log(`info`, `Http server successfully closed`, {})
      this.logger.log(`info`, `closing the database`, {})
      await closeDB();
      this.logger.log(`info`, `Database successfully closed`, {})
    } catch (error) {
      this.logger.log(`error`, error.message, error)
    }
  }

  public async init(): Promise<void> {
    setupStaticFiles(this.express);
    setupMiddlewares(this.express);
    setupRoutest(this.express, this.logger);
    await connectDB(this.logger)
  }

  public start(): void {
    this.server = this.express.listen(Number(process.env.APP_PORT) || 8080, () => {
      this.logger.log(
        `info`,
        `Server listening on port: ${process.env.APP_PORT || 8080}`,
        {}
      );
    });
  }
}

export default ApplicationServer;

工厂:

export const SetupServer = (): Server => {
    const logger = new adptLogger({})
  return new ApplicationServer(logger)
}

开始:

(async () => {
  const server = SetupServer();
  try {
    await server
      .init()
      .then(() => server.start())
  } catch (error) {
    console.error(error)
    server.getLogger().log(`error`, error.message, error)
    process.exit()
  }
})();

这是我的测试::

describe("Hello Word Route", () => {
  let server= {} as Server;
  beforeAll(async () => {
    server = SetupServer();
    await server.init();
    server.start();
  });
  afterAll(async () => {
  });

  it("should return a json with value: hello word", async () => {
    await request(server.getExpress())
      .post("api/hello-word")
      .send({hello: 'hello word'})
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200);
  });
});

我想知道在这种情况下执行路由测试我的测试失败的最佳实践是什么:

 Hello Word Route › should return a json with value: hello word

    listen EADDRINUSE: address already in use :::8080

      50 | 
      51 |   public start(): void {
    > 52 |     this.server = this.express.listen(Number(process.env.APP_PORT) || 8080, () => {
         |                                ^
      53 |       this.logger.log(
      54 |         `info`,
      55 |         `Server listening on port: ${process.env.APP_PORT || 8080}`,

      at Function.listen (node_modules/express/lib/application.js:618:24)
      at ApplicationServer.start (src/application/infra/app.ts:52:32)
      at Object.<anonymous> (src/application/routes/hello-word-routes.test.ts:11:12)

(node:113) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:113) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:113) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

标签: node.jstypescriptjestjs

解决方案


推荐阅读