微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐