Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a post request test in mocha with data to test if response matches?

Tags:

Question: How do would I write a post request test in mocha that tests if the response matches?

The response will just be a url string as it is a redirect for a 3rd party service.

Working Example Payload:

curl -H "Content-Type: application/json" -X POST -d '{"participant":{"nuid":"98ASDF988SDF89SDF89989SDF9898"}}' http://localhost:9000/api/members

member.controller.js // post method

// Creates a new member in the DB.
exports.create = function(req, res) {
  Member.findByIdAndUpdate(req.body.participant.nuid,
    { "$setOnInsert": { "_id": req.body.participant.nuid } },
      { "upsert": true },
      function(err,doc) {
        if (err) throw err;
        res.send({
          'redirectUrl': req.protocol + '://' + req.get('host') + '/registration/' + req.body.participant.nuid
        })
    }
  );
};

Expected res.send

 {"redirectUrl":"http://localhost:9000/registration/98ASDF988SDF89SDF89989SDF9898"}  

Working Example GET request Test

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

describe('GET /api/members', function() {

  it('should respond with JSON array', function(done) {
    request(app)
      .get('/api/members')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function(err, res) {
        if (err) return done(err);
        res.body.should.be.instanceof(Array);
        done();
      });
  });
  it('should respond with redirect on post', function(done) {
    // need help here
  });
});
like image 369
Armeen Harwood Avatar asked Jul 02 '15 05:07

Armeen Harwood


People also ask

How do you test your promises in Mocha?

Create a file named teams. js, import the API using require and create the function getTeamByPlayer it will return a promise, using setTimeout simulate the async process. Our promise return the resolve if the team with the player is found or the reject with an error if not found. Export the function to be used.


1 Answers

Try with this:

  it('should respond with redirect on post', function(done) {
        request(app)
          .post('/api/members')
          .send({"participant":{"nuid":"98ASDF988SDF89SDF89989SDF9898"}})
          .expect(200)
          .expect('Content-Type', /json/)
          .end(function(err, res) {
            if (err) done(err);
            res.body.should.have.property('participant');
            res.body.participant.should.have.property('nuid', '98ASDF988SDF89SDF89989SDF9898');

             });
          done();
      });
like image 182
javierfdezg Avatar answered Sep 25 '22 05:09

javierfdezg