NodeJs和Mocha测试响应

时间:2015-06-08 14:46:04

标签: angularjs node.js mocha

是否可以使用Mocha测试NodeJ的响应?

使用AngularJs到NodeJs的$ http进行GET请求。如果请求成功,则调用此函数:

var successCallback = function (data) {
    var SUCCESS_STATUS_CODE = 200;

    response.set('Content-Type', 'application/json');
    response.send({
        statusCode: SUCCESS_STATUS_CODE,
        data: data
    });
};

我曾尝试使用Sinon监视该函数,并尝试使用Mocha检查请求,但我无法让它们工作。编写测试以检查" response.send"?

的输出的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

要测试来自Node.JS的HTTP调用的响应,您可以使用superagent

创建一个文件夹并安装在mocha和superagent中:

$ npm install superagent
$ npm install mocha

然后使用以下代码创建一个名为test.js的文件:

var request = require('superagent');
var assert = require('assert');

var URL = 'https://www.google.com.bo/#q=nodejs';

describe('Testing an HTTP Response', function () {

  it('should have a status code 200', function (done) {
    this.timeout(9000);

    request
      .get(URL)
      .end(function (err, response) {

        assert.equal(response.status, 200);
        done();

      });

  });

});

然后你可以用mocha

运行它
$ mocha