本文介绍了Sequelize 模型单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 User 续集模型,它有一个 beforeCreate 钩子,它使用 bcrypyt 加密密码.Bcrypyt 由模型使用 require 语句加载为依赖项.

I have a User sequelize model that has a beforeCreate hook that encrypts the password using bcrypyt. Bcrypyt is loaded as a dependency by the model using a require statement.

现在,我正在为我的模型编写测试,我想编写一个测试以确保 bcrypt 在创建时对密码进行哈希处理.

Now, I'm writing my tests for my models and I want to write a test that ensures bcrypt is hashing the password on create.

目前,我在 User 模型中添加了一个 setter 来设置 bcrypt 对象.在我的测试中,我可以使用 sinon 创建一个间谍并使用 setter 注入间谍并确保它在创建时被调用.

At the moment, I have added a setter onto the User model that sets the bcrypt object. In my tests, I can then create a spy using sinon and inject the spy using the setter and ensure it is called on create.

这是正确的做法吗?我觉得我在为我的测试创建一个 setter,它没有其他用途.

Is this the correct way to do it? I feel as if I'm creating a setter purely for my tests and that it serves no other purpose.

推荐答案

如何测试是开发社区中的一个宗教争论点.我认为只要您正在测试,具体如何完成就是一个偏好问题.我倾向于编写尽可能像我的应用程序一样运行的测试.

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.

如果您想确保 bcrypt 在创建时正确散列用户密码,请创建一个用户,保存并检查密码.

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' )
})

这篇关于Sequelize 模型单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:10