测试依赖于TypeORM连接的Express.js路由

huangapple go评论47阅读模式
英文:

Test Express.js routes which rely on a TypeORM connection

问题

以下是代码部分的中文翻译:

我有一个非常基本的Express.js应用程序,我使用Jest和Supertest进行测试。在连接到数据库之前,路由不会设置:

class App {
  public app: express.Application;

  public mainRoutes: Util = new Util();

  constructor() {
    this.app = express();

    AppDataSource.initialize()
      .then(() => {
        // 添加依赖于数据库的路由
        this.mainRoutes.routes(this.app);
      })
      .catch((error) => console.log(error));
  }
}

export default new App().app;

这是我的测试:

describe("Util", function () {
  test("应返回pong对象", async () => {
    const res = await request(app).get("/ping");

    expect(res.statusCode).toEqual(200);
    expect(res.body).toEqual({ message: "pong" });
  });
});

自从我添加了Promise后,就出现了404错误。我无法将async添加到构造函数中。我尝试重构类以将连接与路由设置分离,但似乎没有帮助。

以下代码可以正常工作:

test("应返回pong对象", async () => {
  setTimeout(async () => {
    const res = await request(app).get("/ping");

    expect(res.statusCode).toEqual(200);
    expect(res.body).toEqual({ message: "pong" });
  }, 1000);
});

但显然,我不想添加setTimeout。通常应该如何处理这种情况?我是测试方面的新手。

英文:

I have a very basic Express.js app which I use Jest and Supertest to test. The routes are not set up until the database is connected:

class App {
  public app: express.Application;

  public mainRoutes: Util = new Util();

  constructor() {
    this.app = express();

    AppDataSource.initialize()
      .then(() => {
        // add routes which rely on the database
        this.mainRoutes.routes(this.app);
      })
      .catch((error) => console.log(error));
  }
}

export default new App().app;

Here is my test:

describe("Util", function () {
  test("should return pong object", async () => {
    const res = await request(app).get("/ping");

    expect(res.statusCode).toEqual(200);
    expect(res.body).toEqual({ message: "pong" });
  });
});

Since I put in the promise, this has been 404ing. I can't add async to the constructor. I tried refactoring the class to separate the connection with setting up the routes, but it didn't seem to help.

This works:

test("should return pong object", async () => {
  setTimeout(async () => {
    const res = await request(app).get("/ping");

    expect(res.statusCode).toEqual(200);
    expect(res.body).toEqual({ message: "pong" });
  }, 1000);
});

But obviously I don't want to add a setTimeout. How is this usually done? I am new to testing.

答案1

得分: 1

只需删除 setTimeout() 并等待应用程序的调用。您应该在 beforeAll() 方法中初始化应用程序,我假设您已经有了这个方法,以在测试空间中启动应用程序。您还应该模拟数据库连接,以便可以伪造所需的数据,而不必等待外部数据库实际可用。

// 为您的数据库创建一个模拟,并让它返回您需要的任何内容
import <your-database-class> = require('database');
jest.mock('database', () => {
    // ...
});

describe("Util", function () {

    beforeAll(async () => {
        app = await <whatever you do to launch your application>;
    });

    test('should be defined', () => {
        expect(app).toBeDefined();
    });

    test("should return pong object", async () => {
        const res = await request(app).get("/ping");

        expect(res.statusCode).toEqual(200);
        expect(res.body).toEqual({ message: "pong" });
    });
});

注意:这是您提供的代码的翻译部分,不包括代码本身。

英文:

Just remove the setTimeout() and await the call to the application. You should be initializing the application in the beforeAll() method, which I assume you have, to get the application up and running in the testing space. You should also mock your database connection, so you can fake the data you want back, and not have to wait for the external database to actually be available.

    // Create a mock for your database, and have it return whatever you need
    import &lt;your-database-class&gt; = require(&#39;database&#39;);
    jest.mock(&#39;database&#39;, () =&gt; {
        ...
    });

    describe(&quot;Util&quot;, function () {

    	beforeAll(async () =&gt; {
	    	app = await &lt;whatever you do to launch your application&gt;
    	});

	    test(&#39;should be defined&#39;, () =&gt; {
		    expect(app).toBeDefined();
	    });

        test(&quot;should return pong object&quot;, async () =&gt; {
            const res = await request(app).get(&quot;/ping&quot;);

            expect(res.statusCode).toEqual(200);
            expect(res.body).toEqual({ message: &quot;pong&quot; });
        });
    });

huangapple
  • 本文由 发表于 2023年2月14日 08:22:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442387.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定