Created
November 2, 2016 14:01
-
-
Save ericpkatz/8457d233ebad4e57c7739c2a52f27c9f to your computer and use it in GitHub Desktop.
Sequelize Review
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var expect = require('chai').expect; | |
var Sequelize = require('sequelize'); | |
var db = new Sequelize('postgres://localhost/amazon_db'); | |
var User = db.define('user', { | |
name: { | |
type: Sequelize.STRING, | |
allowNull: false | |
}, | |
foo: { | |
type: Sequelize.STRING, | |
allowNull: false, | |
defaultValue: 'bar' | |
} | |
}, { | |
instanceMethods: { | |
nickname: function(){ | |
return this.name.slice(0, 1); | |
} | |
}, | |
classMethods: { | |
findByName: function(name){ | |
return this.findOne({ | |
where: { name: name } | |
}) | |
} | |
} | |
}); | |
var Book = db.define('book', { | |
title: { | |
type: Sequelize.STRING, | |
allowNull: false | |
} | |
}); | |
Book.belongsTo(User, { as: 'author' }); | |
Book.belongsTo(User, { as: 'reviewer' }); | |
beforeEach(function(){ | |
return db.sync({ force: true }); | |
}); | |
describe('models', function(){ | |
describe('creating books', function(){ | |
it('title is required', function(done){ | |
Book.create() | |
.catch(function(ex){ | |
expect(ex.message).to.equal('notNull Violation: title cannot be null'); | |
done(); | |
}); | |
}); | |
}); | |
describe('creating a book with an author', function(){ | |
var book; | |
beforeEach(function(){ | |
return Book.create({ title: 'Moby Dick' }) | |
.then(function(_book){ | |
book = _book; | |
return Promise.all([ | |
User.create({ name: 'Moe' }), | |
User.create({ name: 'Larry' }) | |
]); | |
}) | |
.then(function(users){ | |
book.authorId = users[0].id; | |
book.reviewerId = users[1].id; | |
return book.save(); | |
}) | |
.then(function(){ | |
return Book.findById(book.id, { | |
include: [ { model: User, as: 'author'}, { model: User, as: 'reviewer'} ] | |
}); | |
}) | |
.then(function(_book){ | |
book = _book; | |
}); | |
}); | |
it('book can be populated with author and reviewer', function(){ | |
expect(book.author.name).to.equal('Moe'); | |
expect(book.reviewer.name).to.equal('Larry'); | |
expect(book.author.nickname()).to.equal('M'); | |
expect(book.reviewer.nickname()).to.equal('L'); | |
expect(book.author.foo).to.equal('bar'); | |
}); | |
describe('getting a user by name', function(done){ | |
it('returns the user', function(){ | |
User.findByName('Moe') | |
.then(function(user){ | |
expect(user.name).to.equal('Moe'); | |
}) | |
.catch(done); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment