2014-05-20 31 views
0

我认为我有一个摩卡和异步/续集的问题。使用sequelize,mocha和async进行单元测试:Sequelize不回拨

我有一个表单,允许用户输入他的伪和密码,并做一些异步的工作。它工作得很好。但是我想为我的所有应用程序编写单元测试。

当我为这部分写测试时,它不起作用,因为sequelize永远不会调用成功函数,我真的不知道为什么,因为它没有摩卡。

这里是表单的处理代码:

var inscrire = function(data, cb){ 
//Getting the data 
var pseudo = data.pseudonyme; 
var password = data.password; 
var passConfirm = data.passwordConfirmation; 
//Verifying the form 
//Pseudonyme 
if(pseudo.length < 1 || password.length > 255){ 
    cb(null, 'form'); 
    return; 
} 
//Password 
if(password.length < 1 || password.length > 255){ 
    cb(null, 'form'); 
    return; 
} 
//Password confirmation 
if(passConfirm != password){ 
    cb(null, 'form'); 
    return; 
} 
async.waterfall([ 
    //Finding the user 
    function(callback){ 
     //Find the user with the pseudonyme 
     db.User.find({where : {'pseudonyme' : pseudo}}).done(function(err, user){ 
      console.log('AAAA'); 
      if(err){ 
       throw err; 
      } 
      console.log('YEAH'); 
      callback(null, user); 
     }); 
    }, 
    //Creating the user if he's not here 
    function(user, callback){ 
     //If the user is not in the base 
     if(!user){ 
      //Hash the password 
      password = hash(password); 
      //Create the user 
      db.User.create({'pseudonyme' : pseudo, 
          'password' : password}).success(function(){ 
       callback(null, true); 
      }); 
     }else{ 
      //The user is alreadyhere 
      callback(null, 'useralreadyhere'); 
     } 
    } 
], function(err, result){ 
    //Throw any exception 
    if(err){ 
     throw err; 
    } 
    //Returning the result 
    cb(null, result); 
}); 

}

这里是我的单元测试的一部分:

describe('#user-not-in-db', function() { 
    it('should succeed', function(){ 
     var data = { 
      'pseudonyme' : 'test', 
      'password' : 'test', 
      'passwordConfirmation' : 'test' 
     }; 
     async.waterfall([ 
      function(callback){ 
       index.inscrire(data, callback); 
      } 
     ], function(err, result){ 
      console.log('YO'); 
      result.should.equal('YOO'); 
     }); 
    }); 
}); 

预先感谢您。

+0

你没忘了初始化/与sequ​​elize连接到数据库的摩卡测试你开始尝试之前查询它? – furydevoid

+0

是的,我将其纳入此处未提及的要求,并且连接正常。但我想我已经找到了什么不起作用,这是因为我不使用异步功能进行不同的测试。既然我已经这样做了,我可以肯定它的工作更多一点。我必须测试,如果它真的工作正常或不 – Sehsyha

回答

1

我看到单元测试至少一个问题,因为你写它:

它的运行作为同步测试。

要在摩卡中运行异步测试,it测试回调必须执行“完成”参数或返回承诺。例如:

describe('foo', function(){ 
    it('must do asyc op', function(done){ 
    async.waterfall([ 
     function(cb){ setTimeout(cb,500); }, 
     function(cb){ cb(null, 'ok'); } 
    ], function(err, res){ 
     assert(res); 
     done(); 
     } 
    ); 
    }); 
}); 

更多的例子参见摩卡文档的一部分:

http://visionmedia.github.io/mocha/#asynchronous-code