jeudi 27 août 2015

Supertest + Tape + Restify - Can't set headers twice error on consecutive calls

I'm building an API using Node.js and Restify. I am trying to do functional endpoint testing using Supertest and Tape. I have a test that makes two consecutive calls to the API and it is saying that I can't set the headers after they are sent.

UserController.js

/*
 * Create a user.
 */
exports.store = function(req, res, next) {
    // Get request input.
    var firstName = ParsesRequest.getValue(req, 'firstName'),
        lastName = ParsesRequest.getValue(req, 'lastName'),
        email = ParsesRequest.getValue(req, 'email'),
        password = ParsesRequest.getValue(req, 'password');

    // Create command.
    var command = new CreateUserCommand(firstName, lastName, email, password);

    // Execute command.
    CommandBus.execute(command, function(error, data) {
        var hasError = !!error && !data,
            status,
            message;

        status = (!hasError) ? StatusCodes.Created : StatusCodes.InternalServerError;
        message = (!hasError) ? UserTransformer.transform(data) : error;

        res.json(status, message);
    });
}

CreatesUserApiTest.js

var test            = require('tape');
var CreatesFakeUser = require('../../helpers/CreatesFakeUser'); 
var request         = require('supertest');
var config          = require('../../../config/Config').getConfiguration('test');
var url             = 'http://' + config.url + ':' + config.port;

test('Creates two users with same email and returns error', function(assert) {
    var user = CreatesFakeUser.generate();

    request(url)
        .post('/user')
        .set('Accept', 'application/json')
        .send(user)
        .expect(201)
        .end(function(err, res){
            assert.equals(res.status, 201, 'Returns 201 as status code.');
            assert.equals(!!res.body.id, true, 'Result body has an id field.');
        });

    request(url)
        .post('/user')
        .set('Accept', 'application/json')
        .send(user)
        .expect(500)
        .end(function(err, res){
            assert.equals(res.status, 500, 'Returns 500 because user already exists.');
            assert.end();
        });
});

Does anyone have any idea why the second request is failing? I am only sending res.json once in my method so it doesn't seem like it should set the headers twice. Also, I'm not sure if it has anything to do with setting the Connection on the header to close, but I tried and it doesn't help. Maybe it has something to do with async.

Any help would be appreciated!

Aucun commentaire:

Enregistrer un commentaire