2

I'm looking for best practices for testing mysql queries with mocha or sinon. I'm trying to test very basic DB queries such as save:

User.prototype.save = function(cb) {

var query = 'INSERT INTO user (name, email, password, img, description)' 
    + 'values (?, ?, ?, ?, ?)';

var params = [this.name, this.email, this.pass, this.img, this.description];

db.query(query, 
    params,
    function(err, rows) {
        if (err) return cb(err);
        cb(rows.insertId);
    }
);
};

I believe I want to make a mock of the database and use that object instead of my db object, but I also want to separate the test logic from the application logic.

I tried variations along the lines of

describe('User', function() {
before(function() {
    mock = sinon.mock(require('../middleware/db'));
})
describe('.save()', function() {
    var uid;
    it('should run save on a user', function() {
        var user = new User ({
            name: 'Test Case 1',
            email: 't1@example.com',
            pass: 'pass',
            img: 'path/to/img.jpg'
        });
        user.save(function(id) {
            id.should.be.ok;
            var uid = id;
        });
    })
    it('should save the user', function() {
        var ret = User.find(uid);
        ret.should.be.ok;
        ret.should.have.property('description');
        ret.name.should.equal('Test Case 1');
        ret.email.should.equal('t1@example.com');
    })
 })

What would be best practices for testing this type of function?

Thanks

BBS
  • 1,351
  • 2
  • 12
  • 27

1 Answers1

0

The actual interaction with the database should not be handled by unit testing but by end to end testing. The best practices for end to end testing with a database are to define a database state which will be loaded into the database before each test.

In terms of unit testing, because this method is a wrapper to call an external module, it's probably enough to defer unit testing to the third party.

BBS
  • 1,351
  • 2
  • 12
  • 27