Sequelize Model Unit Test
I have a User
sequelize model that has a hook beforeCreate
that encrypts the password with bcrypyt
. bcrypyt
loaded as a model dependency using an instruction require
.
Now I am writing my tests for my models and I want to write a test that makes sure it bcrypt
hashes the password when it is created.
At this point, I have added a setter to the model User
that sets the object bcrypt
. In my tests, I can create a spy with sinon
and inject a spy using the installer and make sure it gets called on build.
Is this the correct way to do it? It seems to me that I am creating a setter exclusively for my tests and that it does not serve any other purpose.
source to share
How to test is a point of religious debate in the developer community. I am of the opinion that as long as you are testing, exactly how this is done is a matter of preference. I try to write tests that behave as much as possible like my application.
If you want bcrypt to hashed the user's password correctly on creation, then create the user, save it, and verify the password.
It might be more work with validating the test database for tests, but I believe it provides good results. Both customization and stalling are very handy for scripting.
In this example, you don't even need a test environment to test this behavior.
var User = require( './User' )
var BCRYPT_HASH_BEGINNING = '$2a$'
var TEST_PASSWORD = 'hello there'
User.create({ password: TEST_PASSWORD }).then( function( user ){
if( !user ) throw new Error( 'User is null' )
if( !user.password ) throw new Error( 'Password was not saved' )
if( user.password === TEST_PASSWORD )
throw new Error( 'Password is plaintext' )
if( user.password.indexOf( BCRYPT_HASH_BEGINNING ) === -1 )
throw new Error( 'Password was not encrypted' )
})
source to share