在 NodeJs 中使用 Mocha 测试请求

Testing request with Mocha in NodeJs

我正在创建一个示例网络 scraper 使用 Request API。现在我想用摩卡来测试它。以下代码供参考

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');
        });
    });
});

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

尝试使用 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()
    })
  })