So, I'm a newbie in the TypeScript and Jest world. I've omitted part of my code samples for the sake of simplicity.
Basically, I have a User entity that has a private constructor because I'm using a static factory method in this class. This factory method returns a User instance when success or a list of UserCreationFailures when some provided field is invalid.
My User entity looks like this (please, note that it is just a simplified pseudo-code):
export class User {
// fields
private constructor(name: string, email: string, password: string) {
this.name = name;
this.email = email;
this.password = password;
}
public static create(name: string, email: string, password: string) : UserCreationFailure[], User {
// validations
return failures.length ? failures : new User(name, email, password;
}
}
Also, I'm writing a test to ensures that my factory method works fine. My test looks like this:
it('should create user when all provided fields are valid', () => {
// arrange
// mock User class calling the private constructor
const mockUser = MockUserClass('Bruno', 'bruno@geosapiens.com.br', '12345678');
// act
const result = User.create('Bruno', 'bruno@geosapiens.com.br', '12345678');
// assert
expect(result).toStrictEqual(mockUser);
});
But seems that I cannot use Jest to mock the User class who has a private constructor. I want this mocked user instance in the arrange phase of my test to compare it with the returned user instance by the factory method.
So, my question is: is there a way to use Jest to mock a TypeScript class with a private constructor, passing parameters to it?
I took a look at the Jest documentation about mocks, But I didn't find anything about this specific scenario.
Thanks for the help.