Skip to content

Instantly share code, notes, and snippets.

@crrobinson14
Last active August 29, 2015 14:13
Show Gist options
  • Save crrobinson14/4090e4b393dab2a41458 to your computer and use it in GitHub Desktop.
Save crrobinson14/4090e4b393dab2a41458 to your computer and use it in GitHub Desktop.
Examples of ways to trigger SequelizeJS exceptions so you can more easily test the .catch() branches of query promise chains.
// This mechanism assumes you have an api.models hash of models - adjust to suit your actual location.
api.utils.recursiveDirectoryGlob(__dirname + '/../models', 'js').forEach(function(filename) {
var modelName = (filename.replace(/\\/g, '/').split('/')).pop().replace('.js', '');
console.log('ORM: Loading model ' + modelName);
models[modelName] = sequelize.import(filename);
});
// Pretend we've had a database failure when creating roles
Object.keys(api.models).map(function(modelName) {
api.models[modelName].shouldFail = false;
api.models[modelName].beforeCreate(function(instance, options, callback) {
if (api.models[modelName].shouldFail) {
callback('Unable to process request.');
} else {
callback();
}
});
api.models[modelName].beforeBulkCreate(function(instance, options, callback) {
if (api.models[modelName].shouldFail) {
callback('Unable to process request.');
} else {
callback();
}
});
api.models[modelName].beforeFind(function(options, callback) {
if (api.models[modelName].shouldFail) {
callback('Unable to process request.');
} else {
callback();
}
});
});
// Example usage: Failing a request to a user object
describe('Action: getUser', function() {
// ... Other tests here ...
it('should handle query failures cleanly', function(done) {
api.models.user.shouldFail = true;
api.models.user.findOne(1).then(function(response) {
throw new Error('Query failure test did not throw an exception');
}).catch(function(e) {
assert.that(e, is.not.null());
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment