我想使用Sequelize作为ORM和Mocha / Chai进行单元测试,在mysql数据库上测试CRUD操作。我使用http路由测试了记录的插入/删除,但我直接测试模型而不使用任何http连接。我尝试这样做,但是当我启动测试时,记录没有添加,我没有收到任何错误。
应用/模型/ 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;
};
应用/模型/ 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;
测试/模型/ 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();
});
});
答案 0 :(得分:4)
使用async或promises来确保操作完成。
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();
});
});
});