在NodeJs中使用Mocha进行测试请求

时间:2016-03-17 11:29:47

标签: node.js unit-testing request mocha

我正在使用创建一个示例网络剪贴簿 Request API。现在我想用mocha测试它。以下是供参考的代码。

function requestAll(urlList, cb) {

    var titleList = [],
        counter = urlList.length;

    for (var i = 0; i < urlList.length; i++) {
        request({
            uri: urlList[i]
        }, function (error, response, body) {
            titleList.push(getTitle(response, body));
            counter -= 1;
            if (counter === 0) {
                cb(titleList);
            }
        });
    }
}

这是我正在编写的测试的代码

describe('Request array of URL\'s with Callback', function () {
    it('should return object with titles and URLs for parsed sites', function () {
        utils.requestAll(['http://blog.andrewray.me/how-to-debug-mocha-tests-with-chrome/'], function (titleList) {
            assert.deepEqual(titleList.url, 'http://blog.andrewray.me/how-to-debug-mocha-tests-with-chrome/');
            assert.deepEqual(titleList.title, 'How to Debug Mocha Tests With Chrome');
        });
    });
});

我需要在回调函数中测试它的操作,但我从来没有被引导到它内部。

1 个答案:

答案 0 :(得分:1)

尝试使用superagent测试网络电话:

it('prints "Hello world" when the user goes to /', function(done) {
    superagent.get('http://localhost:3000/', function(error, res) {
      assert.equal(res.status, 200);
      done()
    })
  })