samedi 18 avril 2015

Using supertest and co to validate database content after request

I want to write a test to update a blog post (or whatever): * Insert a blog post in a database * Get the id the blog post got in MongoDb * POST an updated version to my endpoint * After the request have finished: check in the database that update has been done


Here's this, using koa:



var db = require('../lib/db.js');
describe('a test suite', function(){
it('updates an existing text', function (done) {
co(function * () {
var insertedPost = yield db.postCollection.insert({ title : "Title", content : "My awesome content"});
var id = insertedPost._id;
var url = "/post/" + id;
var updatedPost = { content : 'Awesomer content' };

request
.post(url)
.send(updatedTextData)
.expect(302)
.expect('location', url)
.end(function () {
co(function *() {
var p = yield db.postCollection.findById(id);
p.content.should.equal(updatedPost.content);
console.log("CHECKED DB");
})(done());
});
});
});
});


I realize that there's a lot of moving parts in there, but I've tested all the interactions separately. Here's the db-file I've included (which I know works fine since I use it in production):



var monk = require('monk');
var wrap = require('co-monk');

function getCollection(mongoUrl, collectionName) {
var db = monk(mongoUrl);
return wrap(db.get(collectionName));
};

module.exports.postCollection = getCollection([SECRET MONGO CONNECTION], 'posts');


The production code works as intended. This test passes but it seems, to me, like the co-function in the .end()-clause never is run... but the done() call gets made. No "CHECKED DB" is being printed, at least.


I've tried with "done()" and "done" without. Sometimes that works and sometimes not. I've tried to move the check of the database outside the request... but that just hangs, since supertest wants us to call done() when we are completed.


All of this leaves me confused and scared (:)) - what am I doing wrong here.


Aucun commentaire:

Enregistrer un commentaire