[英]how to test node.js http client with mocha?
I have a node.js module that HTTP POSTs a JSON request, 我有一个node.js模块,HTTP POST一个JSON请求,
I want to test for correct url, headers, request body and that the request is actually executed. 我想测试正确的url,标头,请求正文以及请求是否实际执行。
I'm using Mocha for a testing framework. 我正在使用Mocha作为测试框架。 how do I test it ? 我该如何测试呢?
I have used Sinon.js for this type of thing. 我已经将Sinon.js用于此类事情。
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. 为简化测试,MyHttpClient类将请求对象作为构造函数的参数。 If not provided, it just uses require 'request'. 如果没有提供,它只使用require'request'。
Try SuperTest in combination with superagent . 尝试SuperTest结合superagent 。 All the tests from express are written with SuperTest . 来自express的所有测试都是用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);
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.