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