Reputation: 891
I'd like to test CRUD operation on mysql database using Sequelize as ORM and Mocha/Chai for unit testing. I tested the insertion/deleting of record using http routing, but I'd test directly the models without using any http connection. I tried to do it but when I launch the test the record is not added and I don't receive any error.
app/model/article.js
module.exports = function (sequelize, DataTypes) {
var Article = sequelize.define('Article', {
title: DataTypes.STRING,
url: DataTypes.STRING,
text: DataTypes.STRING
}, {
classMethods: {
associate: function (models) {
// example on how to add relations
// Article.hasMany(models.Comments);
}
}
});
return Article;
};
app/model/index.js
var fs = require('fs'),
path = require('path'),
Sequelize = require('sequelize'),
config = require('../../config/config'),
db = {};
var sequelize = new Sequelize(config.db);
fs.readdirSync(__dirname).filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== 'index.js');
}).forEach(function (file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function (modelName) {
if ('associate' in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
test/model/article.js
'use strict';
var expect = require('chai').expect;
var db = require('../../../app/models');
var Article = db.Article;
describe('article', function () {
it('should load', function (done) {
Article.create({
title: 'Titolo',
url: 'URL',
text: 'TEXT'
});
done();
});
});
Upvotes: 4
Views: 6596
Reputation: 963
Either use async or promises to make sure the operation completed.
describe('article', function () {
it('should load', function (done) {
Article.create({
title: 'Titolo',
url: 'URL',
text: 'TEXT'
}).then( function (article) {
// do some tests on article here
done();
});
});
});
Upvotes: 4