5

我有一个 HTTP POST JSON 请求的 node.js 模块,

我想测试正确的 url、标头、请求正文以及请求是否实际执行。

我正在使用 Mocha 作为测试框架。我该如何测试它?

4

3 回答 3

1

你可以使用nock。您可以拦截 http 请求并具有某些属性

于 2013-07-25T02:12:35.800 回答
0

我已经将 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)

为了简化测试 MyHttpClient 类将请求对象作为构造函数的参数。如果没有提供,它只使用 require 'request'。

于 2013-07-25T04:33:24.460 回答
-1

尝试将 SuperTestsuperagent结合使用。express 的所有测试都是用SuperTest编写的。

例如:

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);
  })
})
于 2012-10-11T14:55:41.070 回答