Usman Tahir
Usman Tahir

Reputation: 2663

Testing request with Mocha in NodeJs

I am creating a sample web scraper using Request API. Now I want to test it using mocha. following is code for reference.

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

and this is code for the test I am writing

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

I need to test its operations in call back function, but I am never directed inside it.

Upvotes: 0

Views: 465

Answers (1)

Antonio MG
Antonio MG

Reputation: 20410

Try using superagent to test web calls:

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()
    })
  })

Upvotes: 1

Related Questions