簡體   English   中英

如何使用mocha測試node.js http客戶端?

[英]how to test node.js http client with mocha?

我有一個node.js模塊,HTTP POST一個JSON請求,

我想測試正確的url,標頭,請求正文以及請求是否實際執行。

我正在使用Mocha作為測試框架。 我該如何測試呢?

你可以使用nock 您可以攔截http請求和某些屬性

我已經將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'。

嘗試SuperTest結合superagent 來自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);
  })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM