Search code examples
node.jsexpressmocha.jssequelize.jssupertest

Howto make a unit test with rollback using express, sequelize, mocha and supertests


I´m trying to make a test inserting data into a database, test a request with supertest and then make a rollback with the fake data. Do someone know if this way is correct? If it is not, please could you answer and tell me which is the right way? Thanks in advance.

...

var app = express();
var request = require('supertest');
var assert = require("assert");
var db = require('../../models');
var mysql = require('mysql');

describe('[Test controller - send_confirmation_email.js]', function () {

    describe('POST /crowdfunding/sendConfirmationEmail', function () {

        it('Second post test with data', function (done) {

            db.sequelize.transaction(function (t) {

                var cf = db.Crowdfunding.build({
                    money_raised: 80,
                    project_id: 999,
                    country: 'germany',
                    type: 'SONG',
                    state: 'PENDING'
                });

                cf.save({ transaction: t }).success(function (cf) {

                    request(app)
                    .post('/crowdfunding/sendConfirmationEmail')
                    .send({
                        'id': cf.id,
                        'text': 'test text'
                    })
                    // .expect(500)
                    .end(function (err, res) {
                        assert.equal('PENDING', cf.state);    
                        t.rollback();
                        done();
                    });                        

                }).error(function () { });

            });    
        });    
    });    
});

Solution

  • That looks like you have the right idea in mind, but the control flow timing around the transaction is not right. Here's a few tips.

    • Move the transaction setup to a before handler with a done callback and don't call done until inside the cf.save().success( callback. This will make sure the transaction is done saving before starting your test logic.
    • Move t.rollback(); to a after handler or the transaction will rollback before your test request is sent.
    • Don't forget to assert that the request succeeds with no error and a 200-level status code