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
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'.
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);
})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.