First, let's install it as a development dependency:
$ yarn add bcryptjs --dev
Then, import the genSaltSync and hashSync methods from the bcryptjs module and use them to generate a salt and digest. We will also store the salt and digest in the context to help us make assertions in subsequent steps:
import { genSaltSync, hashSync } from 'bcryptjs';
...
async function createUser() {
...
user.password = crypto.randomBytes(32).toString('hex');
user.salt = genSaltSync(10);
user.digest = hashSync(user.password, user.salt);
const result = await client.index({ index, type, refresh,
body: {
email: user.email,
digest: user.digest,
},
});
...
}
Normally, we would use the asynchronous version of the hash method. However, since we are writing a test, which cannot continue anyway unless this step has completed execution, we can use the synchronous method to save us an extra line returning a promise.
The genSaltSync function has the following function signature:
genSaltSync([rounds, seed_length])
Here, rounds determines how many rounds of hash stretching bcrypt should perform; the higher the number, the slower the digest is to generate and verify. The default is 10, which is what we are using here.
If we run our tests now, the unit and integration tests should still pass, but the E2E tests will fail.