Skip to content

Instantly share code, notes, and snippets.

@alum
Last active August 29, 2015 13:57
Show Gist options
  • Save alum/9630602 to your computer and use it in GitHub Desktop.
Save alum/9630602 to your computer and use it in GitHub Desktop.
Sequelize test of incorrect count() with included relations
/*
To run:
1. npm install sequelize
2. npm install mysql (or whatever you use)
3. edit username and password below
4. node index.js
*/
var Sequelize = require('sequelize')
var Promise = require('bluebird')
var assert = require('assert')
var sequelize = new Sequelize(
'test_count',
'root',
'',
{
host: 'localhost',
port: 3306
})
var Project = sequelize.define('Project', {
id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
project_name: { type: Sequelize.STRING}
})
var User = sequelize.define('User', {
id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
user_name: { type: Sequelize.STRING }
})
User.hasMany(Project)
var userId = null
User.sync()
.then(function() {
return Project.sync()
})
.then(function() {
return User.create()
})
.then(function() {
return Project.create()
})
Promise.all([User.sync(), Project.sync()])
.then(function() {
return Promise.all([User.create(), Project.create(), Project.create(), Project.create()])
})
.then(function(results) {
var user = results[0]
userId = user.id
return user.setProjects([results[1], results[2], results[3]])
})
.then(function() {
return User.findAndCountAll({
where: {id: userId},
include: [Project]
})
})
.then(function(results) {
assert.strictEqual(results.rows.length, 1) // expecting 1 User/row
assert.strictEqual(results.rows[0].projects.length, 3) // expecting 3 Projects
assert.strictEqual(typeof(results.count), 'number') // not sure you want to do type checking, but anyway..
assert.strictEqual(results.count, 1) // expecting count to be 1 for the User
})
.done()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment