Skip to content

Problem in route unit testing

I'm testing the GET ezelectronics/reviews/:model route and I don't understand why the following test fails, giving an error code of 503, instead of 422 as expected:

const baseURL = "/ezelectronics/reviews"
jest.mock("../../src/controllers/reviewController")
jest.mock("../../src/routers/auth")
const testUser: User = new User("test", "test", "test", Role.ADMIN, "test", "test")
test("Express validator param error", async () => {
    jest.spyOn(Authenticator.prototype, "isLoggedIn").mockImplementation((req, res, next) => {
        req.user = testUser
        return next()
    })
    jest.mock('express-validator', () => ({
        param: jest.fn().mockImplementation(() => {
            throw new Error("Invalid value");
        }),
    }));
    jest.spyOn(ErrorHandler.prototype, "validateRequest").mockImplementation((req, res, next) => {
        return res.status(422).json({ error: "The parameters are not formatted properly\n\n" });
    })

    const response = await request(app).get(baseURL + "/Invalid")
    expect(response.status).toBe(422)
})

The route in the reviewController is the following:

this.router.get(
    "/:model",
    this.authenticator.isLoggedIn,
    param("model").exists().isString().isLength({ min: 1 }),
    this.errorHandler.validateRequest,
    (req: any, res: any, next: any) => this.controller.getProductReviews(req.params.model)
        .then((reviews: any/*ProductReview[]*/) => res.status(200).json(reviews))
        .catch((err: Error) => next(err))
)

The strange thing is that the same code, adjusted in the proper way, works fine with the POST ezelectronics/reviews/:model route, so I think the problem is not in the import modules (which I omitted).

Edited by Roberto Cavallero
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information