Sequelize Model Unit Test

半世苍凉 提交于 2019-12-05 14:46:57
JoshWillik

How to test is a point of religious debate in the development community. I'm of the opinion that as long as you are testing, exactly how that gets done is a matter of preference. I tend to write tests that behave like my application as much as possible.

If you want to ensure that bcrypt is properly hashing the user password on create, then create a user, save it, and check the password.

This can be more work with making sure a test DB is running for the tests, but I find it provides good results. And the setup and teardown is very scriptable.

For this example, you don't even need a test framework to test this behaviour.

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' )
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!