Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

463
Vistas
Testing controller with Jest - trying to inject a service to it with no luck

I'm new to testing in nodejs, I have an express backend split into microservices, and I'm currently trying to test the controller in the User directory. The controller has a constructor which gets the user service - which is in charge of making DB operations. It's injected usually with awilix. I've been trying to inject my own mock object, but with no luck. Here's what my userController.test.js looks like:

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);
    })


})

As you can see, I'm passing in my own new object to the UserController constructor, yet when running the tests, I get that it's undefined. Here's how it looks like in the controller:

 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}`);
        }
    }

I just get

    Failed to get user, error: Cannot read property 'getUserById' of undefined
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda