Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

468
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda