mysql-utils
The purpose of this project is to provide some utils for node-mysql.
The two enhancements are:
-
FakeClient
A faker for running jasmine-tests against the database.
This included a new jasmine matcher, toHaveBeenQueriedWith(pattern), which checks if the fake client have been queried with a specific query.
-
startTransaction
A convenience method for starting transactions, which will automatically call
rollback
if an error occur, orcommit
if the queue empties without problems.
Code examples
These examples are not showing off all the features of the fake-client. They will be expanded on at a later date, as well as some actual documentation of the methods.
The unit-tests for transaction shows a bit of the features of the fake-client.
fakeClient
To isolate the mysql-connection:
var utils = require('mysql-utils'),
mysql = utils.mysql,
fakeClient,
clientCreated = function(client) {
fakeClient = client;
};
utils.fakeClient(mysql, clientCreated);
All mysql-calls are then caught by the fake client, and any calls to mysql.createClient() will return the fakeClient instance, which is also passed to the optional clientCreated callback.
Queries can be both mocked and stubbed easily:
// real code
var client = mysql.createClient();
...
function callback(rows) {
var name = getNameFromRows(rows);
function internalCallback(rows) {
doSomething(rows);
}
client.query('select * from table2 where name=?',
[ name ],
internalCallback);
}
client.query('select name from table1', callback);
// test code
// to check if the first query was called:
expect(fakeClient).toHaveBeenQueriedWith(/select.*table1/i);
// to resolve the first query:
var error = null, rows = [ 'returned name' ];
fakeClient.resolveQuery(error, rows);
// to easily resolve all expected queries:
fakeClient.resolveFutureQueries([
{
query: /select.*table2.*where name=returned name/i,
error: null,
rows: theRowsForInternalCall
}
]);
expect(doSomething).toHaveBeenCalledWith(theRowsForInternalCall);
jasmine matchers
The matchers should be attached in the beforeEach()
of each spec requiring
them.
var utils = require('mysql-utils');
beforeEach(function() {
// adding the matchers to the jasmine suite.
utils.matchers.attach(this);
});
transaction
Transactions will not submit any queries to the underlying mysql client until
commit()
is called. If rollback()
is called instead, all queries will be
discarded instead.
If any of the queries fails after commit()
, the transaction will submit a
ROLLBACK
command to the mysql client instead of a COMMIT
.
var utils = require('mysql-utils'),
client = utils.mysql.createClient();
...
var transaction = utils.startTransaction(client);
transaction.query('some query');
transaction.query('query with parameters: ?, ?', [1,2]);
transaction.query('query with callback', someCallback);
transaction.commit();
Dependencies
-
node-mysql is included as a dependency, and will be required in automatically.
-
fasync provides the queue function that startTransaction returns.