node.js – 使用mocha和sinon在节点中模拟http请求

我用express编写了一个NodeJS应用程序代理了一些外部API调用.所以我正在尝试使用Mocha和Sinon编写单元测试.我的目标是测试应用程序没有任何互联网连接,所以我试图模拟https请求并返回模拟回复.

我遇到了一个问题,我无法找到适合我案例的示例或教程.我的节点应用程序在端口8081上侦听http请求,然后将它们代理到另一个站点.我想测试我的应用程序而不必将请求实际发送到那些外部服务器.我在下面尝试它,我把我要发送的json回复发送回server.respondsWith()函数.

我是否以正确的方式与chai进行ajax调用?或者我应该以某种方式在我的应用程序内发送请求.任何帮助表示赞赏.

var assert = require('assert');
var chai = require('chai');
var spies = require('chai-spies');
var chaiHttp = require('chai-http');
var https = require('https');
var should = chai.should();
var expect = chai.expect;
var sinon = require('sinon');

chai.use(spies);
chai.use(chaiHttp);

describe('Car Repository',function() {
  var server;
  before(function() {
    server = sinon.fakeServer.create();
  });

  after(function() {
    server.restore();
  });

  var url = 'http://127.0.0.1:8081';
  it('should succeed and return a list of cars',function(done) {
    server.respondWith('POST','https://api.sandBox.cars.com/v2/token_endpoint',JSON.stringify({"access_token":"1t3E4IykfpJAbuFsdfM2oFAo5raB5vhfOV0hAYe","token_type":"bearer","expires_in":604800}));
    server.respondWith('GET',url+'/cars',JSON.stringify({'test':'this works'}));

    chai.request(url)
      .get('/cars')
      .end(function(err,res) {
        if (err) {
          throw err;
        }

        res.should.have.status(200);
        res.body.should.have.property('test');
        console.log(res.body);

        done();
      });
    });
});

解决方法

查看 Nock库.它完全符合您的要求.

Nock is an HTTP mocking and expectations library for Node.js

Nock can be used to test modules that perform HTTP requests in isolation.

For instance,if a module performs HTTP requests to a CouchDB server or makes HTTP requests to the Amazon API,you can test that module in isolation.

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...