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

464
Views
Probando el controlador con Jest: tratando de inyectarle un servicio sin suerte

Soy nuevo en las pruebas en nodejs, tengo un backend express dividido en microservicios y actualmente estoy tratando de probar el controlador en el directorio de usuarios. El controlador tiene un constructor que obtiene el servicio del usuario, que se encarga de realizar las operaciones de la base de datos. Se inyecta generalmente con awilix. He estado tratando de inyectar mi propio objeto simulado, pero sin suerte. Así es como se ve mi userController.test.js:

 const request = require('supertest') const UserController = require('../controllers/userController.js'); const { mockRequest, mockResponse } = require('../utils/interceptor') const getAllUsers = jest.fn(); const userLogIn = jest.fn(); const getUserById = jest.fn(); const getUserByEmail = jest.fn(); const SearchUsers = jest.fn(); const changePassword = jest.fn(); const ChangeUserPicture = jest.fn(); const addUser = jest.fn(); getUserById.mockReturnValue({ id: 1, name: 'user', email: 'user@example.com' }) userController = new UserController({ getAllUsers, userLogIn, getUserById, getUserByEmail, SearchUsers, changePassword, ChangeUserPicture, addUser }); describe('getuserbyid', () => { test('should fetch a user by id', async () => { let req = mockRequest(); req.params.id = 1; const res = mockResponse(); await userController.getUserById(req, res) .then((res) => console.log(res)) expect(res.mock).toBe({ name: 'user', email: 'user@example.com' }); expect(res.mock.calls.length).toBe(1); }) })

Como puede ver, estoy pasando mi propio objeto nuevo al constructor UserController, pero cuando ejecuto las pruebas, entiendo que no está definido. Así es como se ve en el controlador:

 async getUserById(req, res) { try { return JSON.stringify(await this.userService.getUserById(req)); } catch (error) { console.log(`There Was a Problem Getting User. error: ${error.message}`); return (`Failed to get user, error: ${error.message}`); } }

acabo de recibir

 Failed to get user, error: Cannot read property 'getUserById' of undefined
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!