Enable rollback for your tests that use knex.
Knest works with most test frameworks out there.
npm install knest --save-dev
Example using mocha as the testing framework
This example is part of the knex mocha tests. They can be run using using the following npm script.
npm run test-mocha
const assert = require('assert')
const {
mysql,
users,
resetDatabase,
findUsers,
createUsers,
createUser,
} = require('./index.spec')
const knest = require('./index').bind(null, mysql)
describe('Mocha & Knest', () => {
it('should reset the database user table', () => resetDatabase(mysql))
it('should create user in user table', () =>
knest(trx =>
createUser(trx, users[0]).then(record =>
assert.deepEqual(record, users[0])
)
))
it('should create users using multiple transactions', () =>
knest(trx => createUsers(trx, users)))
it('should have rolled back all the insert queries', () =>
findUsers(mysql).then(result => assert.deepEqual(result, [])))
after(() => process.exit())
})
Knest exports a single function.
What Knest basically does is wrap the test function and adds a knex transaction as the first argument of the test callback function.
returns a promise which will rollback the transaction when it resolves. This is required. Throws if a promise is not returned.
This value should be a knex-connection or a knex transaction object.
The testFn is called when the tests are run. It is called with the following arguments
knexTransaction is an instance of a knex transaction that uses the previously configured knex connection.
Knest is tested using MySQL. Make sure you have MySQL installed. The
./setup.sql
file makes it easy to setup a database and user for running the
tests.
#!/bin/bash
npm install
sudo mysql -p < ./setup.sql
Once the test requirements are setup you can run the tests using npm test
- Simpler function signature for test fn. Use a separate function definition for your test fn and your transaction function. See reference
Some suggestions for contributing to this library are:
- Use this library for your knex related tests.
- Write tests that use different test frameworks.
- Write tests for other databases knex supports.
- Support for multiple connections/transactions
- Contribute what you feel is important.