Search code examples
node.jsmocha.jspg-promise

Unit Test Functions Connecting to a Postgres DB


I am using mocha, nodejs and pg-promise connecting to a Postgres db. I am wondering how can I unit test a function that executes a DML? This is just a simple example:

export function insertUser(db, { firstName, lastName }) {
  db.one(`
    INSERT INTO users
    (
      firstName,
      lastName
    )
    VALUES
    (
      $<firstName>,
      $<lastName>
    )
  `, { firstName, lastName });
}

If there is a typo in the query, how can the unit test capture it? I can create a test db, creating temporary tables on the fly but this will cause my test to slow down.


Solution

  • Given that the db variable is a function parameter, unit-testing this type of code will be straight-forward.

    Go ahead and install a mocking library. We have had good success with sinonjs.

    npm install sinon --save-dev
    

    With the mock library in place you can now create the unit-test, something along the lines as follows:

    const should = require('should'),
          sinon = require('sinon'),
          helper = require('your-db-module');
    
    describe('DB functions', () => {
      describe('insertUser', () => {
        const { insertUser } = helper;
    
        it('correctly inserts a new user', () => {
          const db = {
            one: sinon.stub()
          };
    
          insertUser(db, { firstName: 'john', lastName: 'doe' });
    
          db.one.calledWithExactly('INSERT INTO users(firstName, lastName) VALUES($<firstName>, $<lastName>)', { firstName: 'john', lastName: 'doe'}).should.eql(true);
        });
      });
    });
    

    That should set you off on the right foot.