Reputation: 1250
I have the problem where my unit test with mocha always return an error when i try to create a new instance and save it to the db.
Model:
//db is a global instance of the sequelize pool connection
var sequelize = require('sequelize');
var users = db.define('users', {
uuid: {
type: sequelize.STRING(36),
allowNull: false,
unique: true,
validate: {
isUUID: 4
}
},
username: {
type: sequelize.STRING(100),
allowNull: false,
unique: 'idxProvUsr'
}
}, {
freezeTableName: true
});
module.exports = users;
Controller:
var usersDB = require('../models/users');
var sequelize = require('sequelize');
var usersCtrl = {
userCreate: function (userData, callback) {
var test = usersDB.build(userData);
test.save()
.then(function (data) {
callback(true, data);
})
.catch(function (error) {
if (error) {
callback(false, error);
}
});
},
};
module.exports = usersCtrl;
Test:
'use strict';
var chai = require('chai');
var uuid = require('node-uuid');
var userCtrl = require('../app/controllers/users');
var userData = {
uuid: null,
username: 'manuerumx'
};
describe('Users Controller', function(){
it('Fails add new User', function(done){
userCtrl.userCreate(userData, function(isOk, response){
chai.expect(isOk).to.equal(false);
done();
});
});
it('Add new User', function(done){
userData.uuid = uuid.v4();
userCtrl.userCreate(userData, function(isOk, response){
chai.expect(isOk).to.equal(true);
done();
});
});
});
The first unit tests is ok. The instance is not added because the uuid field is required.
The second, is the problem. The instance is added to database, but the catch instruction return always the same error:
{ [AssertionError: expected true to equal false]
message: 'expected true to equal false',
showDiff: true,
actual: true,
expected: false }
Already tested with the same results:
usersDB.build(userData).save().then(...).catch(...);
usersDB.create(userData).then(...).catch(...);
What i'm doing wrong? Is because i'm using promises with callbacks?
Is not the isUUID validation, i already try to remove it.
Upvotes: 0
Views: 1361
Reputation: 2875
I suppose, the problem is related to async execution. While first test isn't finished, userData.uuid gets value by second. Try to define and pass another user data in second test:
it('Add new User', function(done){
var correctUserData = {
uuid: uuid.v4(),
username: "manuerumx"
};
userCtrl.userCreate(correctUserData, function(isOk, response){
chai.expect(isOk).to.equal(true);
done();
});
});
Upvotes: 1