I have a node.js module that HTTP POSTs a JSON request,
I want to test for correct url, headers, request body and that the request is actually executed.
I'm using Mocha for a testing framework. how do I test it ?
You can use nock. you can intercept the http request and with certain properties
Try SuperTest in combination with superagent. All the tests from express are written with SuperTest.
For example:
var request = require('supertest')
, express = require('express');
var app = express();
app.get('/user', function(req, res){
res.send(201, { name: 'tobi' });
});
describe('GET /users', function(){
it('respond with json', function(done){
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, done);
})
})
I have used Sinon.js for this type of thing.
sinon = require 'sinon'
assert = require "assert"
describe 'client', ->
describe '#mainRequest()', ->
it 'should make the correct HTTP call', ->
url = "http://some.com/api/blah?command=true"
request = {}
sinon.stub request, 'get', (params, cb) -> cb null, { statusCode: 200 }, "OK"
client = new MyHttpClient request
client.sendRequest()
assert.ok request.get.calledWith(url)
To simplify testing MyHttpClient class takes a request object as a paramter to the constructor. If not provided, it just uses require 'request'.