Writing unit tests that verify things are working properly. I'd like to explicitly rollback to avoid committing the test data.
_Post a minimal code sample that reproduces the issue, including models and associations_
var User = sequelize.define("User", {
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
}
});
it('can save a user', () => {
return sequelize.transaction({ autocommit: false }, function (t) {
return User.create({
username: 'testuser'
}, { transaction: t })
.then(user => {
expect(user.id).to.be.greaterThan(0);
return t.rollback();
});
})
.catch(error => {
// Ignore the "error" thrown from an explicit rollback.
if (error.message != 'Transaction cannot be committed because it has been finished with state: rollback') throw error;
});
});
I'd expect it to rollback without throwing an error.
It attempts to commit and throws an error I need to catch to avoid failing the test. (catch included in above code)
_Output, either JSON or SQL_
1 failing
1) models/User can save a user:
Error: Transaction cannot be committed because it has been finished with st
ate: rollback
at Transaction.commit (D:\dev\node\autorenter_nodeexpress_api\node_modules
\sequelize\lib\transaction.js:176:11)
at null.<anonymous> (D:\dev\node\autorenter_nodeexpress_api\node_modules\s
equelize\lib\sequelize.js:1288:30)
at tryCatcher (D:\dev\node\autorenter_nodeexpress_api\node_modules\bluebir
d\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (D:\dev\node\autorenter_nodeexpress_a
pi\node_modules\bluebird\js\release\promise.js:502:31)
at Promise._settlePromise (D:\dev\node\autorenter_nodeexpress_api\node_mod
ules\bluebird\js\release\promise.js:559:18)
at Promise._settlePromise0 (D:\dev\node\autorenter_nodeexpress_api\node_mo
dules\bluebird\js\release\promise.js:604:10)
at Promise._settlePromises (D:\dev\node\autorenter_nodeexpress_api\node_mo
dules\bluebird\js\release\promise.js:683:18)
at Async._drainQueue (D:\dev\node\autorenter_nodeexpress_api\node_modules\
bluebird\js\release\async.js:138:16)
at Async._drainQueues (D:\dev\node\autorenter_nodeexpress_api\node_modules
\bluebird\js\release\async.js:148:10)
at Immediate.Async.drainQueues [as _onImmediate] (D:\dev\node\autorenter_n
odeexpress_api\node_modules\bluebird\js\release\async.js:17:14)
Dialect: postgres
Database version: 9.5.1
Sequelize version: 3.23
Nevermind. Got it. Had to use an "unmanaged transaction".
Transactions
For anyone interested:
it('can save a ' + model.name, () => {
return models.sequelize.transaction({ autocommit: false }).then(function (t) {
return model.create(options, { transaction: t })
.then(user => {
expect(user.id).to.be.greaterThan(0);
return t.rollback();
});
});
});
Most helpful comment
Nevermind. Got it. Had to use an "unmanaged transaction".
Transactions
For anyone interested: