mardi 5 mai 2015

Disconnecting a unit test with express and node-postgres

I'm struggling to find a good way to exit my tests against an express api that queries postgres. On the pg wiki, I found this info to be conceptually helpful, but I can't yet find a way to format my tests correctly.

index.js:

var express = require('express');
var bodyParser = require('body-parser');
var pg = require('pg');
var app = express();
app.use(bodyParser.json());


app.get('/query', function(req, res){

  pg.connect('postgres://user@localhost/db', function(err, client, done){
    var query = client.query('select * from peanuts');
    query.on('end', function(result){
      if (err){
        // handle error
      }
      // release client back to pool
      done();
      res.json({'peanuts': result.rowCount});
    });
  });
});

// export the app so I can run tests
module.exports = app;

test/index.js:

var test = require('tape');
var request = require('supertest');
var app = require('../');

test('/query', function(t){
  request(app)
    .get('/query')
    .expect(200)
    .end(function(err, res){
      t.plan(1);
      t.error(err, 'no error');
    });
});

If a client pool of size 1 is the best option, how do I write the 'teardown' and how can I produce this single-client behavior only in the tests?

Aucun commentaire:

Enregistrer un commentaire