5

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 ?

3 Answers 3

1

You can use nock. you can intercept the http request and with certain properties

Sign up to request clarification or add additional context in comments.

Comments

0

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);
  })
})

1 Comment

@zemirco, how do I pass a live app server to this test file? I prefer to run the test separately from server.
0

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'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.