Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
¿Cómo simular el valor de retorno de middleware en supertest?

Traté de probar mi API usando super test, pero cuando agrego un middleware de autenticación, no sé cómo simular el middleware, aquí está mi código.

authMiddleware.js

 export const authMiddleware = async (req: RequestWithUser, res: Response, next: NextFunction) => { try { const Authorization = req.cookies['Authorization'] || req.header('Authorization').split('Bearer ')[1] || null; if (Authorization) { const secretKey: string = config.get('secretKey'); const verificationResponse = (await jwt.verify(Authorization, secretKey)) as DataStoredInToken; console.log(verificationResponse); const userId = verificationResponse._id; const findUser = await userModel.findById(userId); if (findUser) { req.user = findUser; next(); } else { next(new HttpException(401, 'Wrong authentication token')); } } else { next(new HttpException(404, 'Authentication token missing')); } } catch (error) { next(new HttpException(401, 'Wrong authentication token')); } };
 describe('[GET] /users/:id', () => { it('response findOne User', async () => { const userId = 'qpwoeiruty'; const usersRoute = new UsersRoute(); const users = usersRoute.usersController.userService.users; users.findOne = jest.fn().mockReturnValue({ _id: 'qpwoeiruty', email: 'a@email.com', isAdmin: false, password: await bcrypt.hash('q1w2e3r4!', 10), }); (mongoose as any).connect = jest.fn(); const app = new App([usersRoute]); return request(app.getServer()).get(`${usersRoute.path}/${userId}`).expect(200); }); });

El dúo fallido de la prueba anterior a mi solicitud no tenía autorización en el encabezado, y pienso en establecer el encabezado, pero cuando se trata de

 const finder = await userModel.findById(userId);

esto fallará ya que está relacionado con la acción del servidor y la base de datos real, por lo que no creo que sea la forma correcta de escribir esta prueba.

Lo que quiero hacer es burlarme de mi variable authMiddleware, por ejemplo

 const findUser = jest.fn().mockReturnValue( .... )

para que el middleware de autenticación pueda pasar, ¿cuál es la forma correcta de hacerlo aquí?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!