代码之家  ›  专栏  ›  技术社区  ›  Ming

测试路线的最佳方法

  •  0
  • Ming  · 技术社区  · 4 年前

    我从jest开始,我试图测试一个路由,但是我不知道什么是最好的方法,就像我用docker做的那样,我上docker启动server 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.
    
    0 回复  |  直到 4 年前