import sinon from 'sinon';
import {
createMockPool,
createMockQueryResult,
sql,
} from 'slonik';
import bcrypt from 'bcrypt';const query = sinon
.stub()
.onCall(0)
.returns(
createMockQueryResult([])
)
.onCall(1)
.returns(
createMockQueryResult([
{
id: 'bar',
},
])
)
.onCall(2)
.throws();
const updatePassword = async (connection, userId, newPassowrd) => {
const lastPasswordHash = await connection.maybeOneFirst(sql`
SELECT password_hash
FROM user_account_password
WHERE
user_id = ${userId}
ORDER BY created_at DESC
LIMIT 1
`);
if (lastPasswordHash) {
if (bcrypt.compare(newPassowrd, lastPasswordHash)) {
throw new Error('New password must be different from the last password.');
}
}
await connection.query(sql`
INSERT INTO user_account_password (user_id, password_hash)
VALUES (${userId}, ${bcrypt.hashSync(newPassowrd, 10)})
`);
await connection.query(sql`
UPDATE user_account
SET password = ${bcrypt.hashSync(newPassowrd, 10)}
WHERE id = ${userId}
`);
};
newPassowrd(createMockPool(), 1, 'foo');
// Write assertions about `query` method.
// @see https://sinonjs.org/releases/latest/spies/