我正在尝试为我在Sails.js中创建的模型编写一些测试。该模型如下所示:
/**
* Users
*
* @module :: Model
* @description :: A short summary of how this model works and what it represents.
* @docs :: http://sailsjs.org/#!documentation/models
*/
var User = {
/**
* Attributes list for the user
* @type {Object}
*/
attributes: {
password:{
type: 'string',
alphanumeric: true,
required: true,
minLength: 6
},
firstName: {
type: 'string',
maxLength: 50,
minLength: 5,
required: true
},
lastName:{
type: 'string',
maxLength: 50,
minLength: 5,
required: true
},
email: {
type: 'email',
unique: true,
required: true
}
},
/**
* Function that hashes a password
* @param {Object} attrs - user attributes list
* @param {Function} next [description]
* @return {[type]} [description]
*/
beforeCreate: function( attrs, next ) {
var bcrypt = require('bcrypt');
bcrypt.genSalt( 10, function( err, salt ) {
if ( err ) return next( err );
bcrypt.hash( attrs.password, salt, function( err, hash ) {
if ( err ) return next( err );
attrs.password = hash;
next();
});
});
}
};
module.exports = User;
我写的测试如下所示:
var assert = require('assert')
, Sails = require('sails')
, barrels = require('barrels')
, fixtures;
// Global before hook
before(function (done) {
// Lift Sails with test database
Sails.lift({
log: {
level: 'error'
},
adapters: {
default: 'mongo'
}
}, function(err, sails) {
if (err)
return done(err);
// Load fixtures
barrels.populate(function(err) {
done(err, sails);
});
// Save original objects in `fixtures` variable
fixtures = barrels.objects;
});
});
// Global after hook
after(function (done) {
console.log();
sails.lower(done);
});
// User test
describe('Users', function(done) {
it("should be able to create", function(done) {
Users.create({firstName: "johnny", lastName: "BeGood", email: "johnnybegood@example.com", password: "validpassword123"}, function(err, user) {
assert.notEqual(user, undefined);
done();
});
});
it("should be able to destroy", function(done) {
Users.destroy({email: "johnnybegood@example.com"}, function(err) {
assert.equal(true, true);
});
});
});
但是,我只能通过第一次测试,我收到的输出如下所示:
我很想在节点/风帆中编写测试。在这种情况下,是否有人能指出我在做错的事情。我正在利用以下要点 https://gist.github.com/joukokar/57b14e034e41893407f0
答案 0 :(得分:2)
如果您使用异步Mocha测试,则必须在最后调用回调(done();
):
it("should be able to destroy", function(done) {
Users.destroy({email: "johnnybegood@example.com"}, function(err) {
assert.equal(true, true);
done();
});
});
另外,我会测试assert.ifError(err)
而不是assert.equal(true, true)
(如果代码没有去那里你根本看不到断言,但这并不意味着你实际测试了这个案例)