How does one unit test routes with Express?

后端 未结 8 2177
一整个雨季
一整个雨季 2020-12-07 08:38

I\'m in the process of learning Node.js and have been playing around with Express. Really like the framework;however, I\'m having trouble figuring out how to write a unit/i

8条回答
  •  情深已故
    2020-12-07 09:34

    In my case the only I wanted to test is if the right handler has been called. I wanted to use supertest to laverage the simplicity of making the requests to the routing middleware. I am using Typescript a and this is the solution that worked for me

    // ProductController.ts
    
    import { Request, Response } from "express";
    
    class ProductController {
      getAll(req: Request, res: Response): void {
        console.log("this has not been implemented yet");
      }
    }
    export default ProductController
    

    The routes

    // routes.ts
    import ProductController  from "./ProductController"
    
    const app = express();
    const productController = new ProductController();
    app.get("/product", productController.getAll);
    

    The tests

    // routes.test.ts
    
    import request from "supertest";
    import { Request, Response } from "express";
    
    const mockGetAll = jest
      .fn()
      .mockImplementation((req: Request, res: Response) => {
        res.send({ value: "Hello visitor from the future" });
      });
    
    jest.doMock("./ProductController", () => {
      return jest.fn().mockImplementation(() => {
        return {
          getAll: mockGetAll,
    
        };
      });
    });
    
    import app from "./routes";
    
    describe("Routes", () => {
      beforeEach(() => {
        mockGetAll.mockImplementation((req: Request, res: Response) => {
          res.send({ value: "You can also change the implementation" });
        });
      });
    
      it("GET /product integration test", async () => {
        const result = await request(app).get("/product");
    
        expect(mockGetAll).toHaveBeenCalledTimes(1);
    
      });
    
    
    
      it("GET an undefined route should return status 404", async () => {
        const response = await request(app).get("/random");
        expect(response.status).toBe(404);
      });
    });
    
    
    

    I had some issues to get the mocking to work. but using jest.doMock and the specific order you see in the example makes it work.

提交回复
热议问题