I have just started writing unit tests. I understand that testing private functions is bad practice (with exceptions i guess).
However, i have not found any clear information on the following:
If I test a publicly available function that calls a private one directly, is it okay to mock the private one and ‘call’ it from within the test?
So this is the code i want to test:
async asserUser(
user: CurrentUser,
id: string,
): Promise<void> {
if (!(await this.userHasAccess(user.id, id))) {
throw new ForbiddenException(
'some error message',
);
}
}
I have written this test:
it('should throw an exception', async () => {
const userHasAccessMock = jest.spyOn(
service.prototype as any,
'userHasAccess',
);
userHasAccess.mockReturnValue(false);
expect(() => service.asserUser(mockUser, mockId)).toThrow(
ForbiddenException,
);
});
Is mocking userHasAccess
okay in this context? If yes, have i done it the correct way? If no, how would i proceed in testing this whole thing?
Thanks.
user24671363 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.