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

470
Views
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
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!