I am seeing a behavior that I can not understand. The following test fails to capture the thrown error:
await expect(authService.register({ email, password })).rejects.toThrow();
While this one successfully captures the thrown error:
const register = authService.register;
await expect(register({ email, password })).rejects.toThrow();
I am aware this could be a bug, but this literally does not make sense to me, since expect function receives the exact same Promise in both cases, but still behaves differently. How is this behavior even possible?
Here is the register method of AuthService class if that is gonna be of any help:
async register(cmd: RegisterCmd) {
// check if email already exists
const password = await this.db.getPassword({ email: cmd.email });
if (password) {
throw new ClientError(ErrorKind.BadRequest, 'Email is already registered');
}
// hash password
const hashedPassword = await this.crypt.hash(cmd.password, N);
// save account to database
await this.db.createAccount({ email: cmd.email, password: hashedPassword });
}
I have the following mock return value at the beginning of the test to make sure the password is returned, meaning that the user is already registered, hence it should throw an error.
mockDb.getPassword.mockResolvedValueOnce('pass');
db
and crypt
ports are mocked in the test as following:
beforeAll(() => {
mockDb = mock<IDatabase>();
mockCrypt = mock<ICrypt>();
authService = new AuthService(mockDb, mockCrypt);
});
I am also resetting the mocks here:
afterEach(() => {
jest.resetAllMocks();
});