简体   繁体   中英

Test models using Mocha and Sequelize

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();
  });
});

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();
    });
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM