Skip to content

Instantly share code, notes, and snippets.

@odigity
Last active February 2, 2021 14:34
Show Gist options
  • Save odigity/7f37077de74964051d45c4ca80ec3250 to your computer and use it in GitHub Desktop.
Save odigity/7f37077de74964051d45c4ca80ec3250 to your computer and use it in GitHub Desktop.
Wrapping a unit test in a transaction for easy cleanup with Knex.js
#!/usr/bin/node
const Promise = require('bluebird')
const config = require('./config.json')
const knex = require('./lib/knex')(config.database).connection()
const mock = () => ({ user_id: Math.floor(Math.random() * 999) + 1, payload_type: 'foo', attributes: JSON.stringify({}) })
const before = (t) => {
console.log('before')
const tmp = {}
const p = new Promise( (resolve, reject) => tmp.resolve = resolve )
knex.transaction( tx => { t.tx = tx; tmp.resolve() } ).catch( () => {} )
return p
}
const test = async (t) => {
console.log('test')
let m1 = mock(), m2 = mock()
await t.tx('notifications').insert(m1)
await t.tx('notifications').insert(m2)
}
const after = (t) => {
console.log('after')
// return t.tx.commit()
return t.tx.rollback()
}
let t = {}
before(t)
.then( () => test(t) )
.then( () => after(t) )
.catch( e => console.log(`e: ${e}`) )
@caoer
Copy link

caoer commented Sep 20, 2017

for ava, we can write like this:

test.beforeEach(test => {
  return new Promise(resolve => {
    knex.transaction(function(t) {
        test.context.transaction = t;

        resolve();

        return new Promise(() => {});
      })
      .catch(() => {});  //why things not working if remove this line? 
  });
});

test.afterEach(async test => {
  await test.context.transaction.rollback();
});

I'm just not sure why things will be not working if we removed the empty catch block. any ideas?

@RohanHart
Copy link

RohanHart commented Nov 28, 2017

catch(() => {}); //why things not working if remove this line?

knex turns the rollback into an exception which then fails the ava test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment