不要怂,就是干,撸起袖子干!

Commit c14972b9 by Andy Edwards Committed by GitHub

refactor: asyncify test/unit (#12223)

1 parent 6d116f87
...@@ -89,7 +89,7 @@ const Support = { ...@@ -89,7 +89,7 @@ const Support = {
lastSqliteInstance = _sequelize; lastSqliteInstance = _sequelize;
return _sequelize; return _sequelize;
} }
return Promise.resolve(sequelize); return sequelize;
}, },
createSequelizeInstance(options) { createSequelizeInstance(options) {
...@@ -145,24 +145,22 @@ const Support = { ...@@ -145,24 +145,22 @@ const Support = {
await this.dropTestSchemas(sequelize); await this.dropTestSchemas(sequelize);
}, },
dropTestSchemas(sequelize) { async dropTestSchemas(sequelize) {
const queryInterface = sequelize.getQueryInterface(); const queryInterface = sequelize.getQueryInterface();
if (!queryInterface.queryGenerator._dialect.supports.schemas) { if (!queryInterface.queryGenerator._dialect.supports.schemas) {
return this.sequelize.drop({}); return this.sequelize.drop({});
} }
return sequelize.showAllSchemas().then(schemas => { const schemas = await sequelize.showAllSchemas();
const schemasPromise = []; const schemasPromise = [];
schemas.forEach(schema => { schemas.forEach(schema => {
const schemaName = schema.name ? schema.name : schema; const schemaName = schema.name ? schema.name : schema;
if (schemaName !== sequelize.config.database) { if (schemaName !== sequelize.config.database) {
schemasPromise.push(sequelize.dropSchema(schemaName)); schemasPromise.push(sequelize.dropSchema(schemaName));
} }
});
return Promise.all(schemasPromise.map(p => p.catch(e => e)))
.then(() => {}, () => {});
}); });
await Promise.all(schemasPromise.map(p => p.catch(e => e)));
}, },
getSupportedDialects() { getSupportedDialects() {
......
...@@ -180,14 +180,13 @@ describe(Support.getTestDialectTeaser('belongsToMany'), () => { ...@@ -180,14 +180,13 @@ describe(Support.getTestDialectTeaser('belongsToMany'), () => {
this.destroy.restore(); this.destroy.restore();
}); });
it('uses one insert into statement', function() { it('uses one insert into statement', async function() {
return user.setTasks([task1, task2]).then(() => { await user.setTasks([task1, task2]);
expect(this.findAll).to.have.been.calledOnce; expect(this.findAll).to.have.been.calledOnce;
expect(this.bulkCreate).to.have.been.calledOnce; expect(this.bulkCreate).to.have.been.calledOnce;
});
}); });
it('uses one delete from statement', function() { it('uses one delete from statement', async function() {
this.findAll this.findAll
.onFirstCall().resolves([]) .onFirstCall().resolves([])
.onSecondCall().resolves([ .onSecondCall().resolves([
...@@ -195,12 +194,10 @@ describe(Support.getTestDialectTeaser('belongsToMany'), () => { ...@@ -195,12 +194,10 @@ describe(Support.getTestDialectTeaser('belongsToMany'), () => {
{ userId: 42, taskId: 16 } { userId: 42, taskId: 16 }
]); ]);
return user.setTasks([task1, task2]).then(() => { await user.setTasks([task1, task2]);
return user.setTasks(null); await user.setTasks(null);
}).then(() => { expect(this.findAll).to.have.been.calledTwice;
expect(this.findAll).to.have.been.calledTwice; expect(this.destroy).to.have.been.calledOnce;
expect(this.destroy).to.have.been.calledOnce;
});
}); });
}); });
......
...@@ -46,14 +46,13 @@ describe(Support.getTestDialectTeaser('hasMany'), () => { ...@@ -46,14 +46,13 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
this.update.restore(); this.update.restore();
}); });
it('uses one update statement for addition', function() { it('uses one update statement for addition', async function() {
return user.setTasks([task1, task2]).then(() => { await user.setTasks([task1, task2]);
expect(this.findAll).to.have.been.calledOnce; expect(this.findAll).to.have.been.calledOnce;
expect(this.update).to.have.been.calledOnce; expect(this.update).to.have.been.calledOnce;
});
}); });
it('uses one delete from statement', function() { it('uses one delete from statement', async function() {
this.findAll this.findAll
.onFirstCall().resolves([]) .onFirstCall().resolves([])
.onSecondCall().resolves([ .onSecondCall().resolves([
...@@ -61,13 +60,11 @@ describe(Support.getTestDialectTeaser('hasMany'), () => { ...@@ -61,13 +60,11 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
{ userId: 42, taskId: 16 } { userId: 42, taskId: 16 }
]); ]);
return user.setTasks([task1, task2]).then(() => { await user.setTasks([task1, task2]);
this.update.resetHistory(); this.update.resetHistory();
return user.setTasks(null); await user.setTasks(null);
}).then(() => { expect(this.findAll).to.have.been.calledTwice;
expect(this.findAll).to.have.been.calledTwice; expect(this.update).to.have.been.calledOnce;
expect(this.update).to.have.been.calledOnce;
});
}); });
}); });
...@@ -143,7 +140,7 @@ describe(Support.getTestDialectTeaser('hasMany'), () => { ...@@ -143,7 +140,7 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
idC = Math.random().toString(), idC = Math.random().toString(),
foreignKey = 'user_id'; foreignKey = 'user_id';
it('should fetch associations for a single instance', () => { it('should fetch associations for a single instance', async () => {
const findAll = stub(Task, 'findAll').resolves([ const findAll = stub(Task, 'findAll').resolves([
Task.build({}), Task.build({}),
Task.build({}) Task.build({})
...@@ -159,15 +156,16 @@ describe(Support.getTestDialectTeaser('hasMany'), () => { ...@@ -159,15 +156,16 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
expect(findAll).to.have.been.calledOnce; expect(findAll).to.have.been.calledOnce;
expect(findAll.firstCall.args[0].where).to.deep.equal(where); expect(findAll.firstCall.args[0].where).to.deep.equal(where);
return actual.then(results => { try {
const results = await actual;
expect(results).to.be.an('array'); expect(results).to.be.an('array');
expect(results.length).to.equal(2); expect(results.length).to.equal(2);
}).finally(() => { } finally {
findAll.restore(); findAll.restore();
}); }
}); });
it('should fetch associations for multiple source instances', () => { it('should fetch associations for multiple source instances', async () => {
const findAll = stub(Task, 'findAll').returns( const findAll = stub(Task, 'findAll').returns(
Promise.resolve([ Promise.resolve([
Task.build({ Task.build({
...@@ -196,16 +194,17 @@ describe(Support.getTestDialectTeaser('hasMany'), () => { ...@@ -196,16 +194,17 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
expect(findAll.firstCall.args[0].where[foreignKey]).to.have.property(Op.in); expect(findAll.firstCall.args[0].where[foreignKey]).to.have.property(Op.in);
expect(findAll.firstCall.args[0].where[foreignKey][Op.in]).to.deep.equal([idA, idB, idC]); expect(findAll.firstCall.args[0].where[foreignKey][Op.in]).to.deep.equal([idA, idB, idC]);
return actual.then(result => { try {
const result = await actual;
expect(result).to.be.an('object'); expect(result).to.be.an('object');
expect(Object.keys(result)).to.deep.equal([idA, idB, idC]); expect(Object.keys(result)).to.deep.equal([idA, idB, idC]);
expect(result[idA].length).to.equal(3); expect(result[idA].length).to.equal(3);
expect(result[idB].length).to.equal(1); expect(result[idB].length).to.equal(1);
expect(result[idC].length).to.equal(0); expect(result[idC].length).to.equal(0);
}).finally(() => { } finally {
findAll.restore(); findAll.restore();
}); }
}); });
}); });
describe('association hooks', () => { describe('association hooks', () => {
......
...@@ -20,7 +20,7 @@ describe('connection manager', () => { ...@@ -20,7 +20,7 @@ describe('connection manager', () => {
this.sequelize = Support.createSequelizeInstance(); this.sequelize = Support.createSequelizeInstance();
}); });
it('should resolve connection on dialect connection manager', function() { it('should resolve connection on dialect connection manager', async function() {
const connection = {}; const connection = {};
this.dialect.connectionManager.connect.resolves(connection); this.dialect.connectionManager.connect.resolves(connection);
...@@ -28,12 +28,11 @@ describe('connection manager', () => { ...@@ -28,12 +28,11 @@ describe('connection manager', () => {
const config = {}; const config = {};
return expect(connectionManager._connect(config)).to.eventually.equal(connection).then(() => { await expect(connectionManager._connect(config)).to.eventually.equal(connection);
expect(this.dialect.connectionManager.connect).to.have.been.calledWith(config); expect(this.dialect.connectionManager.connect).to.have.been.calledWith(config);
});
}); });
it('should let beforeConnect hook modify config', function() { it('should let beforeConnect hook modify config', async function() {
const username = Math.random().toString(), const username = Math.random().toString(),
password = Math.random().toString(); password = Math.random().toString();
...@@ -45,25 +44,23 @@ describe('connection manager', () => { ...@@ -45,25 +44,23 @@ describe('connection manager', () => {
const connectionManager = new ConnectionManager(this.dialect, this.sequelize); const connectionManager = new ConnectionManager(this.dialect, this.sequelize);
return connectionManager._connect({}).then(() => { await connectionManager._connect({});
expect(this.dialect.connectionManager.connect).to.have.been.calledWith({ expect(this.dialect.connectionManager.connect).to.have.been.calledWith({
username, username,
password password
});
}); });
}); });
it('should call afterConnect', function() { it('should call afterConnect', async function() {
const spy = sinon.spy(); const spy = sinon.spy();
this.sequelize.afterConnect(spy); this.sequelize.afterConnect(spy);
const connectionManager = new ConnectionManager(this.dialect, this.sequelize); const connectionManager = new ConnectionManager(this.dialect, this.sequelize);
return connectionManager._connect({}).then(() => { await connectionManager._connect({});
expect(spy.callCount).to.equal(1); expect(spy.callCount).to.equal(1);
expect(spy.firstCall.args[0]).to.equal(this.connection); expect(spy.firstCall.args[0]).to.equal(this.connection);
expect(spy.firstCall.args[1]).to.eql({}); expect(spy.firstCall.args[1]).to.eql({});
});
}); });
}); });
...@@ -80,28 +77,26 @@ describe('connection manager', () => { ...@@ -80,28 +77,26 @@ describe('connection manager', () => {
this.sequelize = Support.createSequelizeInstance(); this.sequelize = Support.createSequelizeInstance();
}); });
it('should call beforeDisconnect', function() { it('should call beforeDisconnect', async function() {
const spy = sinon.spy(); const spy = sinon.spy();
this.sequelize.beforeDisconnect(spy); this.sequelize.beforeDisconnect(spy);
const connectionManager = new ConnectionManager(this.dialect, this.sequelize); const connectionManager = new ConnectionManager(this.dialect, this.sequelize);
return connectionManager._disconnect(this.connection).then(() => { await connectionManager._disconnect(this.connection);
expect(spy.callCount).to.equal(1); expect(spy.callCount).to.equal(1);
expect(spy.firstCall.args[0]).to.equal(this.connection); expect(spy.firstCall.args[0]).to.equal(this.connection);
});
}); });
it('should call afterDisconnect', function() { it('should call afterDisconnect', async function() {
const spy = sinon.spy(); const spy = sinon.spy();
this.sequelize.afterDisconnect(spy); this.sequelize.afterDisconnect(spy);
const connectionManager = new ConnectionManager(this.dialect, this.sequelize); const connectionManager = new ConnectionManager(this.dialect, this.sequelize);
return connectionManager._disconnect(this.connection).then(() => { await connectionManager._disconnect(this.connection);
expect(spy.callCount).to.equal(1); expect(spy.callCount).to.equal(1);
expect(spy.firstCall.args[0]).to.equal(this.connection); expect(spy.firstCall.args[0]).to.equal(this.connection);
});
}); });
}); });
}); });
...@@ -37,7 +37,7 @@ if (dialect === 'mssql') { ...@@ -37,7 +37,7 @@ if (dialect === 'mssql') {
this.connectionStub.restore(); this.connectionStub.restore();
}); });
it('connectionManager._connect() does not delete `domain` from config.dialectOptions', function() { it('connectionManager._connect() does not delete `domain` from config.dialectOptions', async function() {
this.connectionStub.returns({ this.connectionStub.returns({
STATE: {}, STATE: {},
state: '', state: '',
...@@ -53,12 +53,11 @@ if (dialect === 'mssql') { ...@@ -53,12 +53,11 @@ if (dialect === 'mssql') {
}); });
expect(this.config.dialectOptions.domain).to.equal('TEST.COM'); expect(this.config.dialectOptions.domain).to.equal('TEST.COM');
return this.instance.dialect.connectionManager._connect(this.config).then(() => { await this.instance.dialect.connectionManager._connect(this.config);
expect(this.config.dialectOptions.domain).to.equal('TEST.COM'); expect(this.config.dialectOptions.domain).to.equal('TEST.COM');
});
}); });
it('connectionManager._connect() should reject if end was called and connect was not', function() { it('connectionManager._connect() should reject if end was called and connect was not', async function() {
this.connectionStub.returns({ this.connectionStub.returns({
STATE: {}, STATE: {},
state: '', state: '',
...@@ -73,14 +72,15 @@ if (dialect === 'mssql') { ...@@ -73,14 +72,15 @@ if (dialect === 'mssql') {
on: () => {} on: () => {}
}); });
return this.instance.dialect.connectionManager._connect(this.config) try {
.catch(err => { await this.instance.dialect.connectionManager._connect(this.config);
expect(err.name).to.equal('SequelizeConnectionError'); } catch (err) {
expect(err.parent.message).to.equal('Connection was closed by remote server'); expect(err.name).to.equal('SequelizeConnectionError');
}); expect(err.parent.message).to.equal('Connection was closed by remote server');
}
}); });
it('connectionManager._connect() should call connect if state is initialized', function() { it('connectionManager._connect() should call connect if state is initialized', async function() {
const connectStub = sinon.stub(); const connectStub = sinon.stub();
const INITIALIZED = { name: 'INITIALIZED' }; const INITIALIZED = { name: 'INITIALIZED' };
this.connectionStub.returns({ this.connectionStub.returns({
...@@ -98,10 +98,8 @@ if (dialect === 'mssql') { ...@@ -98,10 +98,8 @@ if (dialect === 'mssql') {
on: () => {} on: () => {}
}); });
return this.instance.dialect.connectionManager._connect(this.config) await this.instance.dialect.connectionManager._connect(this.config);
.then(() => { expect(connectStub.called).to.equal(true);
expect(connectStub.called).to.equal(true);
});
}); });
}); });
} }
...@@ -31,13 +31,11 @@ if (dialect === 'mssql') { ...@@ -31,13 +31,11 @@ if (dialect === 'mssql') {
}); });
describe('beginTransaction', () => { describe('beginTransaction', () => {
it('should call beginTransaction with correct arguments', () => { it('should call beginTransaction with correct arguments', async () => {
return query._run(connectionStub, 'BEGIN TRANSACTION') await query._run(connectionStub, 'BEGIN TRANSACTION');
.then(() => { expect(connectionStub.beginTransaction.called).to.equal(true);
expect(connectionStub.beginTransaction.called).to.equal(true); expect(connectionStub.beginTransaction.args[0][1]).to.equal('transactionName');
expect(connectionStub.beginTransaction.args[0][1]).to.equal('transactionName'); expect(connectionStub.beginTransaction.args[0][2]).to.equal(tediousIsolationLevel.REPEATABLE_READ);
expect(connectionStub.beginTransaction.args[0][2]).to.equal(tediousIsolationLevel.REPEATABLE_READ);
});
}); });
}); });
......
...@@ -19,7 +19,7 @@ describe('[MYSQL/MARIADB Specific] Query', () => { ...@@ -19,7 +19,7 @@ describe('[MYSQL/MARIADB Specific] Query', () => {
console.log.restore(); console.log.restore();
}); });
it('check iterable', () => { it('check iterable', async () => {
const validWarning = []; const validWarning = [];
const invalidWarning = {}; const invalidWarning = {};
const warnings = [validWarning, undefined, invalidWarning]; const warnings = [validWarning, undefined, invalidWarning];
...@@ -28,10 +28,9 @@ describe('[MYSQL/MARIADB Specific] Query', () => { ...@@ -28,10 +28,9 @@ describe('[MYSQL/MARIADB Specific] Query', () => {
const stub = sinon.stub(query, 'run'); const stub = sinon.stub(query, 'run');
stub.onFirstCall().resolves(warnings); stub.onFirstCall().resolves(warnings);
return query.logWarnings('dummy-results').then(results => { const results = await query.logWarnings('dummy-results');
expect('dummy-results').to.equal(results); expect('dummy-results').to.equal(results);
expect(true).to.equal(console.log.calledOnce); expect(true).to.equal(console.log.calledOnce);
});
}); });
}); });
}); });
...@@ -19,15 +19,14 @@ describe(Support.getTestDialectTeaser('Hooks'), () => { ...@@ -19,15 +19,14 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
}); });
describe('arguments', () => { describe('arguments', () => {
it('hooks can modify passed arguments', function() { it('hooks can modify passed arguments', async function() {
this.Model.addHook('beforeCreate', options => { this.Model.addHook('beforeCreate', options => {
options.answer = 41; options.answer = 41;
}); });
const options = {}; const options = {};
return this.Model.runHooks('beforeCreate', options).then(() => { await this.Model.runHooks('beforeCreate', options);
expect(options.answer).to.equal(41); expect(options.answer).to.equal(41);
});
}); });
}); });
...@@ -60,12 +59,11 @@ describe(Support.getTestDialectTeaser('Hooks'), () => { ...@@ -60,12 +59,11 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
}); });
}); });
it('calls beforeSave/afterSave', function() { it('calls beforeSave/afterSave', async function() {
return this.Model.create({}).then(() => { await this.Model.create({});
expect(this.afterCreateHook).to.have.been.calledOnce; expect(this.afterCreateHook).to.have.been.calledOnce;
expect(this.beforeSaveHook).to.have.been.calledOnce; expect(this.beforeSaveHook).to.have.been.calledOnce;
expect(this.afterSaveHook).to.have.been.calledOnce; expect(this.afterSaveHook).to.have.been.calledOnce;
});
}); });
}); });
...@@ -82,11 +80,10 @@ describe(Support.getTestDialectTeaser('Hooks'), () => { ...@@ -82,11 +80,10 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
this.Model.addHook('afterSave', this.afterSaveHook); this.Model.addHook('afterSave', this.afterSaveHook);
}); });
it('calls beforeSave/afterSave', function() { it('calls beforeSave/afterSave', async function() {
return this.Model.create({}).then(() => { await this.Model.create({});
expect(this.beforeSaveHook).to.have.been.calledOnce; expect(this.beforeSaveHook).to.have.been.calledOnce;
expect(this.afterSaveHook).to.have.been.calledOnce; expect(this.afterSaveHook).to.have.been.calledOnce;
});
}); });
}); });
...@@ -103,11 +100,10 @@ describe(Support.getTestDialectTeaser('Hooks'), () => { ...@@ -103,11 +100,10 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
this.Model.addHook('afterSave', this.afterSaveHook); this.Model.addHook('afterSave', this.afterSaveHook);
}); });
it('calls beforeSave/afterSave', function() { it('calls beforeSave/afterSave', async function() {
return this.Model.create({}).then(() => { await this.Model.create({});
expect(this.beforeSaveHook).to.have.been.calledOnce; expect(this.beforeSaveHook).to.have.been.calledOnce;
expect(this.afterSaveHook).to.have.been.calledOnce; expect(this.afterSaveHook).to.have.been.calledOnce;
});
}); });
}); });
}); });
...@@ -126,31 +122,31 @@ describe(Support.getTestDialectTeaser('Hooks'), () => { ...@@ -126,31 +122,31 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
expect(this.hook3).to.have.been.calledOnce; expect(this.hook3).to.have.been.calledOnce;
}); });
it('using addHook', function() { it('using addHook', async function() {
this.Model.addHook('beforeCreate', this.hook1); this.Model.addHook('beforeCreate', this.hook1);
this.Model.addHook('beforeCreate', this.hook2); this.Model.addHook('beforeCreate', this.hook2);
this.Model.addHook('beforeCreate', this.hook3); this.Model.addHook('beforeCreate', this.hook3);
return this.Model.runHooks('beforeCreate'); await this.Model.runHooks('beforeCreate');
}); });
it('using function', function() { it('using function', async function() {
this.Model.beforeCreate(this.hook1); this.Model.beforeCreate(this.hook1);
this.Model.beforeCreate(this.hook2); this.Model.beforeCreate(this.hook2);
this.Model.beforeCreate(this.hook3); this.Model.beforeCreate(this.hook3);
return this.Model.runHooks('beforeCreate'); await this.Model.runHooks('beforeCreate');
}); });
it('using define', function() { it('using define', async function() {
return current.define('M', {}, { await current.define('M', {}, {
hooks: { hooks: {
beforeCreate: [this.hook1, this.hook2, this.hook3] beforeCreate: [this.hook1, this.hook2, this.hook3]
} }
}).runHooks('beforeCreate'); }).runHooks('beforeCreate');
}); });
it('using a mixture', function() { it('using a mixture', async function() {
const Model = current.define('M', {}, { const Model = current.define('M', {}, {
hooks: { hooks: {
beforeCreate: this.hook1 beforeCreate: this.hook1
...@@ -159,11 +155,11 @@ describe(Support.getTestDialectTeaser('Hooks'), () => { ...@@ -159,11 +155,11 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
Model.beforeCreate(this.hook2); Model.beforeCreate(this.hook2);
Model.addHook('beforeCreate', this.hook3); Model.addHook('beforeCreate', this.hook3);
return Model.runHooks('beforeCreate'); await Model.runHooks('beforeCreate');
}); });
}); });
it('stops execution when a hook throws', function() { it('stops execution when a hook throws', async function() {
this.Model.beforeCreate(() => { this.Model.beforeCreate(() => {
this.hook1(); this.hook1();
...@@ -171,41 +167,38 @@ describe(Support.getTestDialectTeaser('Hooks'), () => { ...@@ -171,41 +167,38 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
}); });
this.Model.beforeCreate(this.hook2); this.Model.beforeCreate(this.hook2);
return expect(this.Model.runHooks('beforeCreate')).to.be.rejected.then(() => { await expect(this.Model.runHooks('beforeCreate')).to.be.rejected;
expect(this.hook1).to.have.been.calledOnce; expect(this.hook1).to.have.been.calledOnce;
expect(this.hook2).not.to.have.been.called; expect(this.hook2).not.to.have.been.called;
});
}); });
it('stops execution when a hook rejects', function() { it('stops execution when a hook rejects', async function() {
this.Model.beforeCreate(() => { this.Model.beforeCreate(async () => {
this.hook1(); this.hook1();
return Promise.reject(new Error('No!')); throw new Error('No!');
}); });
this.Model.beforeCreate(this.hook2); this.Model.beforeCreate(this.hook2);
return expect(this.Model.runHooks('beforeCreate')).to.be.rejected.then(() => { await expect(this.Model.runHooks('beforeCreate')).to.be.rejected;
expect(this.hook1).to.have.been.calledOnce; expect(this.hook1).to.have.been.calledOnce;
expect(this.hook2).not.to.have.been.called; expect(this.hook2).not.to.have.been.called;
});
}); });
}); });
describe('global hooks', () => { describe('global hooks', () => {
describe('using addHook', () => { describe('using addHook', () => {
it('invokes the global hook', function() { it('invokes the global hook', async function() {
const globalHook = sinon.spy(); const globalHook = sinon.spy();
current.addHook('beforeUpdate', globalHook); current.addHook('beforeUpdate', globalHook);
return this.Model.runHooks('beforeUpdate').then(() => { await this.Model.runHooks('beforeUpdate');
expect(globalHook).to.have.been.calledOnce; expect(globalHook).to.have.been.calledOnce;
});
}); });
it('invokes the global hook, when the model also has a hook', () => { it('invokes the global hook, when the model also has a hook', async () => {
const globalHookBefore = sinon.spy(), const globalHookBefore = sinon.spy(),
globalHookAfter = sinon.spy(), globalHookAfter = sinon.spy(),
localHook = sinon.spy(); localHook = sinon.spy();
...@@ -220,14 +213,13 @@ describe(Support.getTestDialectTeaser('Hooks'), () => { ...@@ -220,14 +213,13 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
current.addHook('beforeUpdate', globalHookAfter); current.addHook('beforeUpdate', globalHookAfter);
return Model.runHooks('beforeUpdate').then(() => { await Model.runHooks('beforeUpdate');
expect(globalHookBefore).to.have.been.calledOnce; expect(globalHookBefore).to.have.been.calledOnce;
expect(globalHookAfter).to.have.been.calledOnce; expect(globalHookAfter).to.have.been.calledOnce;
expect(localHook).to.have.been.calledOnce; expect(localHook).to.have.been.calledOnce;
expect(localHook).to.have.been.calledBefore(globalHookBefore); expect(localHook).to.have.been.calledBefore(globalHookBefore);
expect(localHook).to.have.been.calledBefore(globalHookAfter); expect(localHook).to.have.been.calledBefore(globalHookAfter);
});
}); });
}); });
...@@ -243,19 +235,18 @@ describe(Support.getTestDialectTeaser('Hooks'), () => { ...@@ -243,19 +235,18 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
}); });
}); });
it('runs the global hook when no hook is passed', function() { it('runs the global hook when no hook is passed', async function() {
const Model = this.sequelize.define('M', {}, { const Model = this.sequelize.define('M', {}, {
hooks: { hooks: {
beforeUpdate: _.noop // Just to make sure we can define other hooks without overwriting the global one beforeUpdate: _.noop // Just to make sure we can define other hooks without overwriting the global one
} }
}); });
return Model.runHooks('beforeCreate').then(() => { await Model.runHooks('beforeCreate');
expect(this.beforeCreate).to.have.been.calledOnce; expect(this.beforeCreate).to.have.been.calledOnce;
});
}); });
it('does not run the global hook when the model specifies its own hook', function() { it('does not run the global hook when the model specifies its own hook', async function() {
const localHook = sinon.spy(), const localHook = sinon.spy(),
Model = this.sequelize.define('M', {}, { Model = this.sequelize.define('M', {}, {
hooks: { hooks: {
...@@ -263,40 +254,37 @@ describe(Support.getTestDialectTeaser('Hooks'), () => { ...@@ -263,40 +254,37 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
} }
}); });
return Model.runHooks('beforeCreate').then(() => { await Model.runHooks('beforeCreate');
expect(this.beforeCreate).not.to.have.been.called; expect(this.beforeCreate).not.to.have.been.called;
expect(localHook).to.have.been.calledOnce; expect(localHook).to.have.been.calledOnce;
});
}); });
}); });
}); });
describe('#removeHook', () => { describe('#removeHook', () => {
it('should remove hook', function() { it('should remove hook', async function() {
const hook1 = sinon.spy(), const hook1 = sinon.spy(),
hook2 = sinon.spy(); hook2 = sinon.spy();
this.Model.addHook('beforeCreate', 'myHook', hook1); this.Model.addHook('beforeCreate', 'myHook', hook1);
this.Model.beforeCreate('myHook2', hook2); this.Model.beforeCreate('myHook2', hook2);
return this.Model.runHooks('beforeCreate').then(() => { await this.Model.runHooks('beforeCreate');
expect(hook1).to.have.been.calledOnce; expect(hook1).to.have.been.calledOnce;
expect(hook2).to.have.been.calledOnce; expect(hook2).to.have.been.calledOnce;
hook1.resetHistory(); hook1.resetHistory();
hook2.resetHistory(); hook2.resetHistory();
this.Model.removeHook('beforeCreate', 'myHook'); this.Model.removeHook('beforeCreate', 'myHook');
this.Model.removeHook('beforeCreate', 'myHook2'); this.Model.removeHook('beforeCreate', 'myHook2');
return this.Model.runHooks('beforeCreate'); await this.Model.runHooks('beforeCreate');
}).then(() => { expect(hook1).not.to.have.been.called;
expect(hook1).not.to.have.been.called; expect(hook2).not.to.have.been.called;
expect(hook2).not.to.have.been.called;
});
}); });
it('should not remove other hooks', function() { it('should not remove other hooks', async function() {
const hook1 = sinon.spy(), const hook1 = sinon.spy(),
hook2 = sinon.spy(), hook2 = sinon.spy(),
hook3 = sinon.spy(), hook3 = sinon.spy(),
...@@ -307,31 +295,29 @@ describe(Support.getTestDialectTeaser('Hooks'), () => { ...@@ -307,31 +295,29 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
this.Model.beforeCreate('myHook2', hook3); this.Model.beforeCreate('myHook2', hook3);
this.Model.beforeCreate(hook4); this.Model.beforeCreate(hook4);
return this.Model.runHooks('beforeCreate').then(() => { await this.Model.runHooks('beforeCreate');
expect(hook1).to.have.been.calledOnce; expect(hook1).to.have.been.calledOnce;
expect(hook2).to.have.been.calledOnce; expect(hook2).to.have.been.calledOnce;
expect(hook3).to.have.been.calledOnce; expect(hook3).to.have.been.calledOnce;
expect(hook4).to.have.been.calledOnce; expect(hook4).to.have.been.calledOnce;
hook1.resetHistory(); hook1.resetHistory();
hook2.resetHistory(); hook2.resetHistory();
hook3.resetHistory(); hook3.resetHistory();
hook4.resetHistory(); hook4.resetHistory();
this.Model.removeHook('beforeCreate', 'myHook'); this.Model.removeHook('beforeCreate', 'myHook');
return this.Model.runHooks('beforeCreate'); await this.Model.runHooks('beforeCreate');
}).then(() => { expect(hook1).to.have.been.calledOnce;
expect(hook1).to.have.been.calledOnce; expect(hook2).not.to.have.been.called;
expect(hook2).not.to.have.been.called; expect(hook3).to.have.been.calledOnce;
expect(hook3).to.have.been.calledOnce; expect(hook4).to.have.been.calledOnce;
expect(hook4).to.have.been.calledOnce;
});
}); });
}); });
describe('#addHook', () => { describe('#addHook', () => {
it('should add additional hook when previous exists', function() { it('should add additional hook when previous exists', async function() {
const hook1 = sinon.spy(), const hook1 = sinon.spy(),
hook2 = sinon.spy(); hook2 = sinon.spy();
...@@ -341,44 +327,43 @@ describe(Support.getTestDialectTeaser('Hooks'), () => { ...@@ -341,44 +327,43 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
Model.addHook('beforeCreate', hook2); Model.addHook('beforeCreate', hook2);
return Model.runHooks('beforeCreate').then(() => { await Model.runHooks('beforeCreate');
expect(hook1).to.have.been.calledOnce; expect(hook1).to.have.been.calledOnce;
expect(hook2).to.have.been.calledOnce; expect(hook2).to.have.been.calledOnce;
});
}); });
}); });
describe('promises', () => { describe('promises', () => {
it('can return a promise', function() { it('can return a promise', async function() {
this.Model.beforeBulkCreate(() => { this.Model.beforeBulkCreate(async () => {
return Promise.resolve(); // This space intentionally left blank
}); });
return expect(this.Model.runHooks('beforeBulkCreate')).to.be.fulfilled; await expect(this.Model.runHooks('beforeBulkCreate')).to.be.fulfilled;
}); });
it('can return undefined', function() { it('can return undefined', async function() {
this.Model.beforeBulkCreate(() => { this.Model.beforeBulkCreate(() => {
// This space intentionally left blank // This space intentionally left blank
}); });
return expect(this.Model.runHooks('beforeBulkCreate')).to.be.fulfilled; await expect(this.Model.runHooks('beforeBulkCreate')).to.be.fulfilled;
}); });
it('can return an error by rejecting', function() { it('can return an error by rejecting', async function() {
this.Model.beforeCreate(() => { this.Model.beforeCreate(async () => {
return Promise.reject(new Error('Forbidden')); throw new Error('Forbidden');
}); });
return expect(this.Model.runHooks('beforeCreate')).to.be.rejectedWith('Forbidden'); await expect(this.Model.runHooks('beforeCreate')).to.be.rejectedWith('Forbidden');
}); });
it('can return an error by throwing', function() { it('can return an error by throwing', async function() {
this.Model.beforeCreate(() => { this.Model.beforeCreate(() => {
throw new Error('Forbidden'); throw new Error('Forbidden');
}); });
return expect(this.Model.runHooks('beforeCreate')).to.be.rejectedWith('Forbidden'); await expect(this.Model.runHooks('beforeCreate')).to.be.rejectedWith('Forbidden');
}); });
}); });
......
...@@ -51,21 +51,21 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -51,21 +51,21 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
expect(_validateAndRunHooks).to.not.have.been.called; expect(_validateAndRunHooks).to.not.have.been.called;
}); });
it('fulfills when validation is successful', function() { it('fulfills when validation is successful', async function() {
const instanceValidator = new InstanceValidator(this.User.build()); const instanceValidator = new InstanceValidator(this.User.build());
const result = instanceValidator.validate(); const result = instanceValidator.validate();
return expect(result).to.be.fulfilled; await expect(result).to.be.fulfilled;
}); });
it('rejects with a validation error when validation fails', function() { it('rejects with a validation error when validation fails', async function() {
const instanceValidator = new InstanceValidator(this.User.build({ fails: true })); const instanceValidator = new InstanceValidator(this.User.build({ fails: true }));
const result = instanceValidator.validate(); const result = instanceValidator.validate();
return expect(result).to.be.rejectedWith(SequelizeValidationError); await expect(result).to.be.rejectedWith(SequelizeValidationError);
}); });
it('has a useful default error message for not null validation failures', () => { it('has a useful default error message for not null validation failures', async () => {
const User = Support.sequelize.define('user', { const User = Support.sequelize.define('user', {
name: { name: {
type: Support.Sequelize.STRING, type: Support.Sequelize.STRING,
...@@ -76,7 +76,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -76,7 +76,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
const instanceValidator = new InstanceValidator(User.build()); const instanceValidator = new InstanceValidator(User.build());
const result = instanceValidator.validate(); const result = instanceValidator.validate();
return expect(result).to.be.rejectedWith(SequelizeValidationError, /user\.name cannot be null/); await expect(result).to.be.rejectedWith(SequelizeValidationError, /user\.name cannot be null/);
}); });
}); });
...@@ -86,19 +86,18 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -86,19 +86,18 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
sinon.stub(this.successfulInstanceValidator, '_validate').resolves(); sinon.stub(this.successfulInstanceValidator, '_validate').resolves();
}); });
it('should run beforeValidate and afterValidate hooks when _validate is successful', function() { it('should run beforeValidate and afterValidate hooks when _validate is successful', async function() {
const beforeValidate = sinon.spy(); const beforeValidate = sinon.spy();
const afterValidate = sinon.spy(); const afterValidate = sinon.spy();
this.User.beforeValidate(beforeValidate); this.User.beforeValidate(beforeValidate);
this.User.afterValidate(afterValidate); this.User.afterValidate(afterValidate);
return expect(this.successfulInstanceValidator._validateAndRunHooks()).to.be.fulfilled.then(() => { await expect(this.successfulInstanceValidator._validateAndRunHooks()).to.be.fulfilled;
expect(beforeValidate).to.have.been.calledOnce; expect(beforeValidate).to.have.been.calledOnce;
expect(afterValidate).to.have.been.calledOnce; expect(afterValidate).to.have.been.calledOnce;
});
}); });
it('should run beforeValidate hook but not afterValidate hook when _validate is unsuccessful', function() { it('should run beforeValidate hook but not afterValidate hook when _validate is unsuccessful', async function() {
const failingInstanceValidator = new InstanceValidator(this.User.build()); const failingInstanceValidator = new InstanceValidator(this.User.build());
sinon.stub(failingInstanceValidator, '_validate').rejects(new Error()); sinon.stub(failingInstanceValidator, '_validate').rejects(new Error());
const beforeValidate = sinon.spy(); const beforeValidate = sinon.spy();
...@@ -106,52 +105,48 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -106,52 +105,48 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
this.User.beforeValidate(beforeValidate); this.User.beforeValidate(beforeValidate);
this.User.afterValidate(afterValidate); this.User.afterValidate(afterValidate);
return expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected.then(() => { await expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected;
expect(beforeValidate).to.have.been.calledOnce; expect(beforeValidate).to.have.been.calledOnce;
expect(afterValidate).to.not.have.been.called; expect(afterValidate).to.not.have.been.called;
});
}); });
it('should emit an error from after hook when afterValidate fails', function() { it('should emit an error from after hook when afterValidate fails', async function() {
this.User.afterValidate(() => { this.User.afterValidate(() => {
throw new Error('after validation error'); throw new Error('after validation error');
}); });
return expect(this.successfulInstanceValidator._validateAndRunHooks()).to.be.rejectedWith('after validation error'); await expect(this.successfulInstanceValidator._validateAndRunHooks()).to.be.rejectedWith('after validation error');
}); });
describe('validatedFailed hook', () => { describe('validatedFailed hook', () => {
it('should call validationFailed hook when validation fails', function() { it('should call validationFailed hook when validation fails', async function() {
const failingInstanceValidator = new InstanceValidator(this.User.build()); const failingInstanceValidator = new InstanceValidator(this.User.build());
sinon.stub(failingInstanceValidator, '_validate').rejects(new Error()); sinon.stub(failingInstanceValidator, '_validate').rejects(new Error());
const validationFailedHook = sinon.spy(); const validationFailedHook = sinon.spy();
this.User.validationFailed(validationFailedHook); this.User.validationFailed(validationFailedHook);
return expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected.then(() => { await expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected;
expect(validationFailedHook).to.have.been.calledOnce; expect(validationFailedHook).to.have.been.calledOnce;
});
}); });
it('should not replace the validation error in validationFailed hook by default', function() { it('should not replace the validation error in validationFailed hook by default', async function() {
const failingInstanceValidator = new InstanceValidator(this.User.build()); const failingInstanceValidator = new InstanceValidator(this.User.build());
sinon.stub(failingInstanceValidator, '_validate').rejects(new SequelizeValidationError()); sinon.stub(failingInstanceValidator, '_validate').rejects(new SequelizeValidationError());
const validationFailedHook = sinon.stub().resolves(); const validationFailedHook = sinon.stub().resolves();
this.User.validationFailed(validationFailedHook); this.User.validationFailed(validationFailedHook);
return expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected.then(err => { const err = await expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected;
expect(err.name).to.equal('SequelizeValidationError'); expect(err.name).to.equal('SequelizeValidationError');
});
}); });
it('should replace the validation error if validationFailed hook creates a new error', function() { it('should replace the validation error if validationFailed hook creates a new error', async function() {
const failingInstanceValidator = new InstanceValidator(this.User.build()); const failingInstanceValidator = new InstanceValidator(this.User.build());
sinon.stub(failingInstanceValidator, '_validate').rejects(new SequelizeValidationError()); sinon.stub(failingInstanceValidator, '_validate').rejects(new SequelizeValidationError());
const validationFailedHook = sinon.stub().throws(new Error('validation failed hook error')); const validationFailedHook = sinon.stub().throws(new Error('validation failed hook error'));
this.User.validationFailed(validationFailedHook); this.User.validationFailed(validationFailedHook);
return expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected.then(err => { const err = await expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected;
expect(err.message).to.equal('validation failed hook error'); expect(err.message).to.equal('validation failed hook error');
});
}); });
}); });
}); });
......
...@@ -8,7 +8,7 @@ const chai = require('chai'), ...@@ -8,7 +8,7 @@ const chai = require('chai'),
describe(Support.getTestDialectTeaser('Instance'), () => { describe(Support.getTestDialectTeaser('Instance'), () => {
describe('build', () => { describe('build', () => {
it('should populate NOW default values', () => { it('should populate NOW default values', async () => {
const Model = current.define('Model', { const Model = current.define('Model', {
created_time: { created_time: {
type: DataTypes.DATE, type: DataTypes.DATE,
...@@ -45,7 +45,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => { ...@@ -45,7 +45,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
expect(instance.get('updated_time')).to.be.ok; expect(instance.get('updated_time')).to.be.ok;
expect(instance.get('updated_time')).to.be.an.instanceof(Date); expect(instance.get('updated_time')).to.be.an.instanceof(Date);
return instance.validate(); await instance.validate();
}); });
it('should populate explicitly undefined UUID primary keys', () => { it('should populate explicitly undefined UUID primary keys', () => {
......
...@@ -78,9 +78,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => { ...@@ -78,9 +78,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
describe('custom setter', () => { describe('custom setter', () => {
before(function() { before(function() {
this.stubCreate = sinon.stub(current.getQueryInterface(), 'insert').callsFake(instance => { this.stubCreate = sinon.stub(current.getQueryInterface(), 'insert').callsFake(async instance => [instance, 1]);
return Promise.resolve([instance, 1]);
});
}); });
after(function() { after(function() {
...@@ -103,52 +101,48 @@ describe(Support.getTestDialectTeaser('Instance'), () => { ...@@ -103,52 +101,48 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
} }
}); });
it('does not set field to changed if field is set to the same value with custom setter using primitive value', () => { it('does not set field to changed if field is set to the same value with custom setter using primitive value', async () => {
const user = User.build({ const user = User.build({
phoneNumber: '+1 234 567' phoneNumber: '+1 234 567'
}); });
return user.save().then(() => { await user.save();
expect(user.changed('phoneNumber')).to.be.false; expect(user.changed('phoneNumber')).to.be.false;
user.set('phoneNumber', '+1 (0) 234567'); // Canonical equivalent of existing phone number user.set('phoneNumber', '+1 (0) 234567');// Canonical equivalent of existing phone number
expect(user.changed('phoneNumber')).to.be.false; expect(user.changed('phoneNumber')).to.be.false;
});
}); });
it('sets field to changed if field is set to the another value with custom setter using primitive value', () => { it('sets field to changed if field is set to the another value with custom setter using primitive value', async () => {
const user = User.build({ const user = User.build({
phoneNumber: '+1 234 567' phoneNumber: '+1 234 567'
}); });
return user.save().then(() => { await user.save();
expect(user.changed('phoneNumber')).to.be.false; expect(user.changed('phoneNumber')).to.be.false;
user.set('phoneNumber', '+1 (0) 765432'); // Canonical non-equivalent of existing phone number user.set('phoneNumber', '+1 (0) 765432');// Canonical non-equivalent of existing phone number
expect(user.changed('phoneNumber')).to.be.true; expect(user.changed('phoneNumber')).to.be.true;
});
}); });
it('does not set field to changed if field is set to the same value with custom setter using object', () => { it('does not set field to changed if field is set to the same value with custom setter using object', async () => {
const user = User.build({ const user = User.build({
phoneNumber: '+1 234 567' phoneNumber: '+1 234 567'
}); });
return user.save().then(() => { await user.save();
expect(user.changed('phoneNumber')).to.be.false; expect(user.changed('phoneNumber')).to.be.false;
user.set('phoneNumber', { country: '1', area: '234', local: '567' }); // Canonical equivalent of existing phone number user.set('phoneNumber', { country: '1', area: '234', local: '567' });// Canonical equivalent of existing phone number
expect(user.changed('phoneNumber')).to.be.false; expect(user.changed('phoneNumber')).to.be.false;
});
}); });
it('sets field to changed if field is set to the another value with custom setter using object', () => { it('sets field to changed if field is set to the another value with custom setter using object', async () => {
const user = User.build({ const user = User.build({
phoneNumber: '+1 234 567' phoneNumber: '+1 234 567'
}); });
return user.save().then(() => { await user.save();
expect(user.changed('phoneNumber')).to.be.false; expect(user.changed('phoneNumber')).to.be.false;
user.set('phoneNumber', { country: '1', area: '765', local: '432' }); // Canonical non-equivalent of existing phone number user.set('phoneNumber', { country: '1', area: '765', local: '432' });// Canonical non-equivalent of existing phone number
expect(user.changed('phoneNumber')).to.be.true; expect(user.changed('phoneNumber')).to.be.true;
});
}); });
}); });
}); });
......
...@@ -30,14 +30,14 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -30,14 +30,14 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
describe('validations', () => { describe('validations', () => {
it('should not fail for renamed fields', function() { it('should not fail for renamed fields', async function() {
return this.Model.bulkCreate([ await this.Model.bulkCreate([
{ accountId: 42 } { accountId: 42 }
], { validate: true }).then(() => { ], { validate: true });
expect(this.stub.getCall(0).args[1]).to.deep.equal([
{ account_id: 42, id: null } expect(this.stub.getCall(0).args[1]).to.deep.equal([
]); { account_id: 42, id: null }
}); ]);
}); });
}); });
}); });
......
...@@ -38,32 +38,28 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -38,32 +38,28 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
describe('should pass the same options to model.aggregate as findAndCountAll', () => { describe('should pass the same options to model.aggregate as findAndCountAll', () => {
it('with includes', function() { it('with includes', async function() {
const queryObject = { const queryObject = {
include: [this.Project] include: [this.Project]
}; };
return this.User.count(queryObject) await this.User.count(queryObject);
.then(() => this.User.findAndCountAll(queryObject)) await this.User.findAndCountAll(queryObject);
.then(() => { const count = this.stub.getCall(0).args;
const count = this.stub.getCall(0).args; const findAndCountAll = this.stub.getCall(1).args;
const findAndCountAll = this.stub.getCall(1).args; expect(count).to.eql(findAndCountAll);
expect(count).to.eql(findAndCountAll);
});
}); });
it('attributes should be stripped in case of findAndCountAll', function() { it('attributes should be stripped in case of findAndCountAll', async function() {
const queryObject = { const queryObject = {
attributes: ['username'] attributes: ['username']
}; };
return this.User.count(queryObject) await this.User.count(queryObject);
.then(() => this.User.findAndCountAll(queryObject)) await this.User.findAndCountAll(queryObject);
.then(() => { const count = this.stub.getCall(0).args;
const count = this.stub.getCall(0).args; const findAndCountAll = this.stub.getCall(1).args;
const findAndCountAll = this.stub.getCall(1).args; expect(count).not.to.eql(findAndCountAll);
expect(count).not.to.eql(findAndCountAll); count[2].attributes = undefined;
count[2].attributes = undefined; expect(count).to.eql(findAndCountAll);
expect(count).to.eql(findAndCountAll);
});
}); });
}); });
......
...@@ -30,14 +30,13 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -30,14 +30,13 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.count.resetBehavior(); this.count.resetBehavior();
}); });
it('with errors in count and findAll both', function() { it('with errors in count and findAll both', async function() {
return this.User.findAndCountAll({}) try {
.then(() => { await this.User.findAndCountAll({});
throw new Error(); throw new Error();
}) } catch (err) {
.catch(() => { expect(this.stub.callCount).to.eql(0);
expect(this.stub.callCount).to.eql(0); }
});
}); });
}); });
}); });
......
...@@ -19,34 +19,34 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -19,34 +19,34 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.sinon.restore(); this.sinon.restore();
}); });
it('should return the result of the first find call if not empty', function() { it('should return the result of the first find call if not empty', async function() {
const result = {}, const result = {},
where = { prop: Math.random().toString() }, where = { prop: Math.random().toString() },
findSpy = this.sinon.stub(Model, 'findOne').resolves(result); findSpy = this.sinon.stub(Model, 'findOne').resolves(result);
return expect(Model.findCreateFind({ await expect(Model.findCreateFind({
where where
})).to.eventually.eql([result, false]).then(() => { })).to.eventually.eql([result, false]);
expect(findSpy).to.have.been.calledOnce;
expect(findSpy.getCall(0).args[0].where).to.equal(where); expect(findSpy).to.have.been.calledOnce;
}); expect(findSpy.getCall(0).args[0].where).to.equal(where);
}); });
it('should create if first find call is empty', function() { it('should create if first find call is empty', async function() {
const result = {}, const result = {},
where = { prop: Math.random().toString() }, where = { prop: Math.random().toString() },
createSpy = this.sinon.stub(Model, 'create').resolves(result); createSpy = this.sinon.stub(Model, 'create').resolves(result);
this.sinon.stub(Model, 'findOne').resolves(null); this.sinon.stub(Model, 'findOne').resolves(null);
return expect(Model.findCreateFind({ await expect(Model.findCreateFind({
where where
})).to.eventually.eql([result, true]).then(() => { })).to.eventually.eql([result, true]);
expect(createSpy).to.have.been.calledWith(where);
}); expect(createSpy).to.have.been.calledWith(where);
}); });
it('should do a second find if create failed do to unique constraint', function() { it('should do a second find if create failed do to unique constraint', async function() {
const result = {}, const result = {},
where = { prop: Math.random().toString() }, where = { prop: Math.random().toString() },
findSpy = this.sinon.stub(Model, 'findOne'); findSpy = this.sinon.stub(Model, 'findOne');
...@@ -56,12 +56,12 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -56,12 +56,12 @@ describe(Support.getTestDialectTeaser('Model'), () => {
findSpy.onFirstCall().resolves(null); findSpy.onFirstCall().resolves(null);
findSpy.onSecondCall().resolves(result); findSpy.onSecondCall().resolves(result);
return expect(Model.findCreateFind({ await expect(Model.findCreateFind({
where where
})).to.eventually.eql([result, false]).then(() => { })).to.eventually.eql([result, false]);
expect(findSpy).to.have.been.calledTwice;
expect(findSpy.getCall(1).args[0].where).to.equal(where); expect(findSpy).to.have.been.calledTwice;
}); expect(findSpy.getCall(1).args[0].where).to.equal(where);
}); });
}); });
}); });
...@@ -34,25 +34,23 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -34,25 +34,23 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.clsStub.restore(); this.clsStub.restore();
}); });
it('should use transaction from cls if available', function() { it('should use transaction from cls if available', async function() {
const options = { const options = {
where: { where: {
name: 'John' name: 'John'
} }
}; };
return this.User.findOrCreate(options) try {
.then(() => { await this.User.findOrCreate(options);
expect.fail('expected to fail'); expect.fail('expected to fail');
}) } catch (err) {
.catch(err => { if (!/abort/.test(err.message)) throw err;
if (!/abort/.test(err.message)) throw err; expect(this.clsStub.calledOnce).to.equal(true, 'expected to ask for transaction');
expect(this.clsStub.calledOnce).to.equal(true, 'expected to ask for transaction'); }
});
}); });
it('should not use transaction from cls if provided as argument', function() { it('should not use transaction from cls if provided as argument', async function() {
const options = { const options = {
where: { where: {
name: 'John' name: 'John'
...@@ -60,14 +58,13 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -60,14 +58,13 @@ describe(Support.getTestDialectTeaser('Model'), () => {
transaction: { id: 123 } transaction: { id: 123 }
}; };
return this.User.findOrCreate(options) try {
.then(() => { await this.User.findOrCreate(options);
expect.fail('expected to fail'); expect.fail('expected to fail');
}) } catch (err) {
.catch(err => { if (!/abort/.test(err.message)) throw err;
if (!/abort/.test(err.message)) throw err; expect(this.clsStub.called).to.equal(false);
expect(this.clsStub.called).to.equal(false); }
});
}); });
}); });
}); });
...@@ -71,63 +71,63 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -71,63 +71,63 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
describe('attributes include / exclude', () => { describe('attributes include / exclude', () => {
it('allows me to include additional attributes', function() { it('allows me to include additional attributes', async function() {
return Model.findAll({ await Model.findAll({
attributes: { attributes: {
include: ['foobar'] include: ['foobar']
} }
}).then(() => {
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id',
'name',
'foobar'
]);
}); });
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id',
'name',
'foobar'
]);
}); });
it('allows me to exclude attributes', function() { it('allows me to exclude attributes', async function() {
return Model.findAll({ await Model.findAll({
attributes: { attributes: {
exclude: ['name'] exclude: ['name']
} }
}).then(() => {
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id'
]);
}); });
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id'
]);
}); });
it('include takes precendence over exclude', function() { it('include takes precendence over exclude', async function() {
return Model.findAll({ await Model.findAll({
attributes: { attributes: {
exclude: ['name'], exclude: ['name'],
include: ['name'] include: ['name']
} }
}).then(() => {
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id',
'name'
]);
}); });
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id',
'name'
]);
}); });
it('works for models without PK #4607', function() { it('works for models without PK #4607', async function() {
const Model = current.define('model', {}, { timestamps: false }); const Model = current.define('model', {}, { timestamps: false });
const Foo = current.define('foo'); const Foo = current.define('foo');
Model.hasOne(Foo); Model.hasOne(Foo);
Model.removeAttribute('id'); Model.removeAttribute('id');
return Model.findAll({ await Model.findAll({
attributes: { attributes: {
include: ['name'] include: ['name']
}, },
include: [Foo] include: [Foo]
}).then(() => {
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'name'
]);
}); });
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'name'
]);
}); });
}); });
......
...@@ -23,15 +23,14 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -23,15 +23,14 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
describe('should not add limit when querying on a primary key', () => { describe('should not add limit when querying on a primary key', () => {
it('with id primary key', function() { it('with id primary key', async function() {
const Model = current.define('model'); const Model = current.define('model');
return Model.findOne({ where: { id: 42 } }).then(() => { await Model.findOne({ where: { id: 42 } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit'); expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
}); });
it('with custom primary key', function() { it('with custom primary key', async function() {
const Model = current.define('model', { const Model = current.define('model', {
uid: { uid: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
...@@ -40,12 +39,11 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -40,12 +39,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return Model.findOne({ where: { uid: 42 } }).then(() => { await Model.findOne({ where: { uid: 42 } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit'); expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
}); });
it('with blob primary key', function() { it('with blob primary key', async function() {
const Model = current.define('model', { const Model = current.define('model', {
id: { id: {
type: DataTypes.BLOB, type: DataTypes.BLOB,
...@@ -54,22 +52,20 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -54,22 +52,20 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return Model.findOne({ where: { id: Buffer.from('foo') } }).then(() => { await Model.findOne({ where: { id: Buffer.from('foo') } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit'); expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
}); });
}); });
it('should add limit when using { $ gt on the primary key', function() { it('should add limit when using { $ gt on the primary key', async function() {
const Model = current.define('model'); const Model = current.define('model');
return Model.findOne({ where: { id: { [Op.gt]: 42 } } }).then(() => { await Model.findOne({ where: { id: { [Op.gt]: 42 } } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').to.have.property('limit'); expect(this.stub.getCall(0).args[0]).to.be.an('object').to.have.property('limit');
});
}); });
describe('should not add limit when querying on an unique key', () => { describe('should not add limit when querying on an unique key', () => {
it('with custom unique key', function() { it('with custom unique key', async function() {
const Model = current.define('model', { const Model = current.define('model', {
unique: { unique: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
...@@ -77,12 +73,11 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -77,12 +73,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return Model.findOne({ where: { unique: 42 } }).then(() => { await Model.findOne({ where: { unique: 42 } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit'); expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
}); });
it('with blob unique key', function() { it('with blob unique key', async function() {
const Model = current.define('model', { const Model = current.define('model', {
unique: { unique: {
type: DataTypes.BLOB, type: DataTypes.BLOB,
...@@ -90,13 +85,12 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -90,13 +85,12 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return Model.findOne({ where: { unique: Buffer.from('foo') } }).then(() => { await Model.findOne({ where: { unique: Buffer.from('foo') } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit'); expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
}); });
}); });
it('should add limit when using multi-column unique key', function() { it('should add limit when using multi-column unique key', async function() {
const Model = current.define('model', { const Model = current.define('model', {
unique1: { unique1: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
...@@ -108,9 +102,8 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -108,9 +102,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
} }
}); });
return Model.findOne({ where: { unique1: 42 } }).then(() => { await Model.findOne({ where: { unique1: 42 } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').to.have.property('limit'); expect(this.stub.getCall(0).args[0]).to.be.an('object').to.have.property('limit');
});
}); });
}); });
}); });
...@@ -32,16 +32,14 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -32,16 +32,14 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}); });
describe('properly clones input values', () => { describe('properly clones input values', () => {
it('with default options', function() { it('with default options', async function() {
return this.User.update(this.updates, { where: { secretValue: '1' } }).then(() => { await this.User.update(this.updates, { where: { secretValue: '1' } });
expect(this.updates).to.be.deep.eql(this.cloneUpdates); expect(this.updates).to.be.deep.eql(this.cloneUpdates);
});
}); });
it('when using fields option', function() { it('when using fields option', async function() {
return this.User.update(this.updates, { where: { secretValue: '1' }, fields: ['name'] }).then(() => { await this.User.update(this.updates, { where: { secretValue: '1' }, fields: ['name'] });
expect(this.updates).to.be.deep.eql(this.cloneUpdates); expect(this.updates).to.be.deep.eql(this.cloneUpdates);
});
}); });
}); });
......
...@@ -51,48 +51,45 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -51,48 +51,45 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.stub.restore(); this.stub.restore();
}); });
it('skip validations for missing fields', function() { it('skip validations for missing fields', async function() {
return expect(this.User.upsert({ await expect(this.User.upsert({
name: 'Grumpy Cat' name: 'Grumpy Cat'
})).not.to.be.rejectedWith(Sequelize.ValidationError); })).not.to.be.rejectedWith(Sequelize.ValidationError);
}); });
it('creates new record with correct field names', function() { it('creates new record with correct field names', async function() {
return this.User await this.User
.upsert({ .upsert({
name: 'Young Cat', name: 'Young Cat',
virtualValue: 999 virtualValue: 999
})
.then(() => {
expect(Object.keys(this.stub.getCall(0).args[1])).to.deep.equal([
'name', 'value', 'created_at', 'updatedAt'
]);
}); });
expect(Object.keys(this.stub.getCall(0).args[1])).to.deep.equal([
'name', 'value', 'created_at', 'updatedAt'
]);
}); });
it('creates new record with timestamps disabled', function() { it('creates new record with timestamps disabled', async function() {
return this.UserNoTime await this.UserNoTime
.upsert({ .upsert({
name: 'Young Cat' name: 'Young Cat'
})
.then(() => {
expect(Object.keys(this.stub.getCall(0).args[1])).to.deep.equal([
'name'
]);
}); });
expect(Object.keys(this.stub.getCall(0).args[1])).to.deep.equal([
'name'
]);
}); });
it('updates all changed fields by default', function() { it('updates all changed fields by default', async function() {
return this.User await this.User
.upsert({ .upsert({
name: 'Old Cat', name: 'Old Cat',
virtualValue: 111 virtualValue: 111
})
.then(() => {
expect(Object.keys(this.stub.getCall(0).args[2])).to.deep.equal([
'name', 'value', 'updatedAt'
]);
}); });
expect(Object.keys(this.stub.getCall(0).args[2])).to.deep.equal([
'name', 'value', 'updatedAt'
]);
}); });
}); });
} }
......
...@@ -181,7 +181,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -181,7 +181,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
const applyFailTest = function applyFailTest(validatorDetails, i, validator) { const applyFailTest = function applyFailTest(validatorDetails, i, validator) {
const failingValue = validatorDetails.fail[i]; const failingValue = validatorDetails.fail[i];
it(`correctly specifies an instance as invalid using a value of "${failingValue}" for the validation "${validator}"`, function() { it(`correctly specifies an instance as invalid using a value of "${failingValue}" for the validation "${validator}"`, async function() {
const validations = {}, const validations = {},
message = `${validator}(${failingValue})`; message = `${validator}(${failingValue})`;
...@@ -197,15 +197,14 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -197,15 +197,14 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
const failingUser = UserFail.build({ name: failingValue }); const failingUser = UserFail.build({ name: failingValue });
return expect(failingUser.validate()).to.be.rejected.then(_errors => { const _errors = await expect(failingUser.validate()).to.be.rejected;
expect(_errors.get('name')[0].message).to.equal(message); expect(_errors.get('name')[0].message).to.equal(message);
expect(_errors.get('name')[0].value).to.equal(failingValue); expect(_errors.get('name')[0].value).to.equal(failingValue);
});
}); });
}, },
applyPassTest = function applyPassTest(validatorDetails, j, validator, type) { applyPassTest = function applyPassTest(validatorDetails, j, validator, type) {
const succeedingValue = validatorDetails.pass[j]; const succeedingValue = validatorDetails.pass[j];
it(`correctly specifies an instance as valid using a value of "${succeedingValue}" for the validation "${validator}"`, function() { it(`correctly specifies an instance as valid using a value of "${succeedingValue}" for the validation "${validator}"`, async function() {
const validations = {}, const validations = {},
message = `${validator}(${succeedingValue})`; message = `${validator}(${succeedingValue})`;
...@@ -227,7 +226,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -227,7 +226,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
} }
}); });
const successfulUser = UserSuccess.build({ name: succeedingValue }); const successfulUser = UserSuccess.build({ name: succeedingValue });
return expect(successfulUser.validate()).not.to.be.rejected; await expect(successfulUser.validate()).not.to.be.rejected;
}); });
}; };
...@@ -272,7 +271,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -272,7 +271,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}); });
before(function() { before(function() {
this.stub = sinon.stub(current, 'query').callsFake(() => Promise.resolve([User.build({}), 1])); this.stub = sinon.stub(current, 'query').callsFake(async () => Promise.resolve([User.build({}), 1]));
}); });
after(function() { after(function() {
...@@ -281,34 +280,34 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -281,34 +280,34 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
describe('should not throw', () => { describe('should not throw', () => {
describe('create', () => { describe('create', () => {
it('should allow number as a string', () => { it('should allow number as a string', async () => {
return expect(User.create({ await expect(User.create({
age: '12' age: '12'
})).not.to.be.rejected; })).not.to.be.rejected;
}); });
it('should allow decimal as a string', () => { it('should allow decimal as a string', async () => {
return expect(User.create({ await expect(User.create({
number: '12.6' number: '12.6'
})).not.to.be.rejected; })).not.to.be.rejected;
}); });
it('should allow dates as a string', () => { it('should allow dates as a string', async () => {
return expect(User.findOne({ await expect(User.findOne({
where: { where: {
date: '2000-12-16' date: '2000-12-16'
} }
})).not.to.be.rejected; })).not.to.be.rejected;
}); });
it('should allow decimal big numbers as a string', () => { it('should allow decimal big numbers as a string', async () => {
return expect(User.create({ await expect(User.create({
number: '2321312301230128391820831289123012' number: '2321312301230128391820831289123012'
})).not.to.be.rejected; })).not.to.be.rejected;
}); });
it('should allow decimal as scientific notation', () => { it('should allow decimal as scientific notation', async () => {
return Promise.all([expect(User.create({ await Promise.all([expect(User.create({
number: '2321312301230128391820e219' number: '2321312301230128391820e219'
})).not.to.be.rejected, expect(User.create({ })).not.to.be.rejected, expect(User.create({
number: '2321312301230128391820e+219' number: '2321312301230128391820e+219'
...@@ -317,34 +316,34 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -317,34 +316,34 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
})).to.be.rejected]); })).to.be.rejected]);
}); });
it('should allow string as a number', () => { it('should allow string as a number', async () => {
return expect(User.create({ await expect(User.create({
name: 12 name: 12
})).not.to.be.rejected; })).not.to.be.rejected;
}); });
it('should allow 0/1 as a boolean', () => { it('should allow 0/1 as a boolean', async () => {
return expect(User.create({ await expect(User.create({
awesome: 1 awesome: 1
})).not.to.be.rejected; })).not.to.be.rejected;
}); });
it('should allow 0/1 string as a boolean', () => { it('should allow 0/1 string as a boolean', async () => {
return expect(User.create({ await expect(User.create({
awesome: '1' awesome: '1'
})).not.to.be.rejected; })).not.to.be.rejected;
}); });
it('should allow true/false string as a boolean', () => { it('should allow true/false string as a boolean', async () => {
return expect(User.create({ await expect(User.create({
awesome: 'true' awesome: 'true'
})).not.to.be.rejected; })).not.to.be.rejected;
}); });
}); });
describe('findAll', () => { describe('findAll', () => {
it('should allow $in', () => { it('should allow $in', async () => {
return expect(User.findAll({ await expect(User.findAll({
where: { where: {
name: { name: {
[Op.like]: { [Op.like]: {
...@@ -355,8 +354,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -355,8 +354,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
})).not.to.be.rejected; })).not.to.be.rejected;
}); });
it('should allow $like for uuid', () => { it('should allow $like for uuid', async () => {
return expect(User.findAll({ await expect(User.findAll({
where: { where: {
uid: { uid: {
[Op.like]: '12345678%' [Op.like]: '12345678%'
...@@ -370,8 +369,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -370,8 +369,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
describe('should throw validationerror', () => { describe('should throw validationerror', () => {
describe('create', () => { describe('create', () => {
it('should throw when passing string', () => { it('should throw when passing string', async () => {
return expect(User.create({ await expect(User.create({
age: 'jan' age: 'jan'
})).to.be.rejectedWith(Sequelize.ValidationError) })).to.be.rejectedWith(Sequelize.ValidationError)
.which.eventually.have.property('errors') .which.eventually.have.property('errors')
...@@ -388,8 +387,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -388,8 +387,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}); });
}); });
it('should throw when passing decimal', () => { it('should throw when passing decimal', async () => {
return expect(User.create({ await expect(User.create({
age: 4.5 age: 4.5
})).to.be.rejectedWith(Sequelize.ValidationError) })).to.be.rejectedWith(Sequelize.ValidationError)
.which.eventually.have.property('errors') .which.eventually.have.property('errors')
...@@ -408,8 +407,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -408,8 +407,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}); });
describe('update', () => { describe('update', () => {
it('should throw when passing string', () => { it('should throw when passing string', async () => {
return expect(User.update({ await expect(User.update({
age: 'jan' age: 'jan'
}, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError) }, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError)
.which.eventually.have.property('errors') .which.eventually.have.property('errors')
...@@ -426,8 +425,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -426,8 +425,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}); });
}); });
it('should throw when passing decimal', () => { it('should throw when passing decimal', async () => {
return expect(User.update({ await expect(User.update({
age: 4.5 age: 4.5
}, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError) }, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError)
.which.eventually.have.property('errors') .which.eventually.have.property('errors')
...@@ -484,8 +483,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -484,8 +483,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
describe('should not throw', () => { describe('should not throw', () => {
describe('create', () => { describe('create', () => {
it('custom validation functions are successful', () => { it('custom validation functions are successful', async () => {
return expect(User.create({ await expect(User.create({
age: 1, age: 1,
name: 'noerror' name: 'noerror'
})).not.to.be.rejected; })).not.to.be.rejected;
...@@ -493,8 +492,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -493,8 +492,8 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
}); });
describe('update', () => { describe('update', () => {
it('custom validation functions are successful', () => { it('custom validation functions are successful', async () => {
return expect(User.update({ await expect(User.update({
age: 1, age: 1,
name: 'noerror' name: 'noerror'
}, { where: {} })).not.to.be.rejected; }, { where: {} })).not.to.be.rejected;
...@@ -505,28 +504,28 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -505,28 +504,28 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
describe('should throw validationerror', () => { describe('should throw validationerror', () => {
describe('create', () => { describe('create', () => {
it('custom attribute validation function fails', () => { it('custom attribute validation function fails', async () => {
return expect(User.create({ await expect(User.create({
age: -1 age: -1
})).to.be.rejectedWith(Sequelize.ValidationError); })).to.be.rejectedWith(Sequelize.ValidationError);
}); });
it('custom model validation function fails', () => { it('custom model validation function fails', async () => {
return expect(User.create({ await expect(User.create({
name: 'error' name: 'error'
})).to.be.rejectedWith(Sequelize.ValidationError); })).to.be.rejectedWith(Sequelize.ValidationError);
}); });
}); });
describe('update', () => { describe('update', () => {
it('custom attribute validation function fails', () => { it('custom attribute validation function fails', async () => {
return expect(User.update({ await expect(User.update({
age: -1 age: -1
}, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError); }, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError);
}); });
it('when custom model validation function fails', () => { it('when custom model validation function fails', async () => {
return expect(User.update({ await expect(User.update({
name: 'error' name: 'error'
}, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError); }, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError);
}); });
...@@ -540,11 +539,10 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -540,11 +539,10 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
name: Sequelize.STRING name: Sequelize.STRING
}, { }, {
validate: { validate: {
customFn() { async customFn() {
if (this.get('name') === 'error') { if (this.get('name') === 'error') {
return Promise.reject(new Error('Error from model validation promise')); throw new Error('Error from model validation promise');
} }
return Promise.resolve();
} }
} }
}); });
...@@ -559,16 +557,16 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -559,16 +557,16 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
describe('should not throw', () => { describe('should not throw', () => {
describe('create', () => { describe('create', () => {
it('custom model validation functions are successful', () => { it('custom model validation functions are successful', async () => {
return expect(User.create({ await expect(User.create({
name: 'noerror' name: 'noerror'
})).not.to.be.rejected; })).not.to.be.rejected;
}); });
}); });
describe('update', () => { describe('update', () => {
it('custom model validation functions are successful', () => { it('custom model validation functions are successful', async () => {
return expect(User.update({ await expect(User.update({
name: 'noerror' name: 'noerror'
}, { where: {} })).not.to.be.rejected; }, { where: {} })).not.to.be.rejected;
}); });
...@@ -578,16 +576,16 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -578,16 +576,16 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
describe('should throw validationerror', () => { describe('should throw validationerror', () => {
describe('create', () => { describe('create', () => {
it('custom model validation function fails', () => { it('custom model validation function fails', async () => {
return expect(User.create({ await expect(User.create({
name: 'error' name: 'error'
})).to.be.rejectedWith(Sequelize.ValidationError); })).to.be.rejectedWith(Sequelize.ValidationError);
}); });
}); });
describe('update', () => { describe('update', () => {
it('when custom model validation function fails', () => { it('when custom model validation function fails', async () => {
return expect(User.update({ await expect(User.update({
name: 'error' name: 'error'
}, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError); }, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError);
}); });
...@@ -631,21 +629,21 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -631,21 +629,21 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
this.customValidator.resetHistory(); this.customValidator.resetHistory();
}); });
it('on create', function() { it('on create', async function() {
return expect(this.User.create({ await expect(this.User.create({
age: 10, age: 10,
name: null name: null
})).not.to.be.rejected.then(() => { })).not.to.be.rejected;
return expect(this.customValidator).to.have.been.calledOnce;
}); await expect(this.customValidator).to.have.been.calledOnce;
}); });
it('on update', function() { it('on update', async function() {
return expect(this.User.update({ await expect(this.User.update({
age: 10, age: 10,
name: null name: null
}, { where: {} })).not.to.be.rejected.then(() => { }, { where: {} })).not.to.be.rejected;
return expect(this.customValidator).to.have.been.calledOnce;
}); await expect(this.customValidator).to.have.been.calledOnce;
}); });
}); });
...@@ -654,21 +652,21 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -654,21 +652,21 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
this.customValidator.resetHistory(); this.customValidator.resetHistory();
}); });
it('on create', function() { it('on create', async function() {
return expect(this.User.create({ await expect(this.User.create({
age: 11, age: 11,
name: null name: null
})).to.be.rejectedWith(Sequelize.ValidationError).then(() => { })).to.be.rejectedWith(Sequelize.ValidationError);
return expect(this.customValidator).to.have.been.calledOnce;
}); await expect(this.customValidator).to.have.been.calledOnce;
}); });
it('on update', function() { it('on update', async function() {
return expect(this.User.update({ await expect(this.User.update({
age: 11, age: 11,
name: null name: null
}, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError).then(() => { }, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError);
return expect(this.customValidator).to.have.been.calledOnce;
}); await expect(this.customValidator).to.have.been.calledOnce;
}); });
}); });
...@@ -700,21 +698,21 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -700,21 +698,21 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
this.customValidator.resetHistory(); this.customValidator.resetHistory();
}); });
it('on create', function() { it('on create', async function() {
return expect(this.User.create({ await expect(this.User.create({
age: 99, age: 99,
name: null name: null
})).to.be.rejectedWith(Sequelize.ValidationError).then(() => { })).to.be.rejectedWith(Sequelize.ValidationError);
return expect(this.customValidator).to.have.not.been.called;
}); await expect(this.customValidator).to.have.not.been.called;
}); });
it('on update', function() { it('on update', async function() {
return expect(this.User.update({ await expect(this.User.update({
age: 99, age: 99,
name: null name: null
}, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError).then(() => { }, { where: {} })).to.be.rejectedWith(Sequelize.ValidationError);
return expect(this.customValidator).to.have.not.been.called;
}); await expect(this.customValidator).to.have.not.been.called;
}); });
}); });
...@@ -723,21 +721,21 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => { ...@@ -723,21 +721,21 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
this.customValidator.resetHistory(); this.customValidator.resetHistory();
}); });
it('on create', function() { it('on create', async function() {
return expect(this.User.create({ await expect(this.User.create({
age: 99, age: 99,
name: 'foo' name: 'foo'
})).not.to.be.rejected.then(() => { })).not.to.be.rejected;
return expect(this.customValidator).to.have.been.calledOnce;
}); await expect(this.customValidator).to.have.been.calledOnce;
}); });
it('on update', function() { it('on update', async function() {
return expect(this.User.update({ await expect(this.User.update({
age: 99, age: 99,
name: 'foo' name: 'foo'
}, { where: {} })).not.to.be.rejected.then(() => { }, { where: {} })).not.to.be.rejected;
return expect(this.customValidator).to.have.been.calledOnce;
}); await expect(this.customValidator).to.have.been.calledOnce;
}); });
}); });
......
...@@ -33,7 +33,7 @@ describe('Transaction', () => { ...@@ -33,7 +33,7 @@ describe('Transaction', () => {
this.stubConnection.restore(); this.stubConnection.restore();
}); });
it('should run auto commit query only when needed', function() { it('should run auto commit query only when needed', async function() {
const expectations = { const expectations = {
all: [ all: [
'START TRANSACTION;' 'START TRANSACTION;'
...@@ -45,13 +45,13 @@ describe('Transaction', () => { ...@@ -45,13 +45,13 @@ describe('Transaction', () => {
'BEGIN TRANSACTION;' 'BEGIN TRANSACTION;'
] ]
}; };
return current.transaction(() => {
await current.transaction(async () => {
expect(this.stub.args.map(arg => arg[0])).to.deep.equal(expectations[dialect] || expectations.all); expect(this.stub.args.map(arg => arg[0])).to.deep.equal(expectations[dialect] || expectations.all);
return Promise.resolve();
}); });
}); });
it('should set isolation level correctly', function() { it('should set isolation level correctly', async function() {
const expectations = { const expectations = {
all: [ all: [
'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;', 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;',
...@@ -69,9 +69,9 @@ describe('Transaction', () => { ...@@ -69,9 +69,9 @@ describe('Transaction', () => {
'BEGIN TRANSACTION;' 'BEGIN TRANSACTION;'
] ]
}; };
return current.transaction({ isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED }, () => {
await current.transaction({ isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED }, async () => {
expect(this.stub.args.map(arg => arg[0])).to.deep.equal(expectations[dialect] || expectations.all); expect(this.stub.args.map(arg => arg[0])).to.deep.equal(expectations[dialect] || expectations.all);
return Promise.resolve();
}); });
}); });
}); });
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!