Search code examples
javascriptnode.jssupertestsuperagent

Getting "TypeError: object is not a function" when using supertest/superagent in forEach loop


I'm using supertest to test a set of URLs by the same rules.

var urls = [
    "https://www.example.com",
    "https://www.example2.com"
];

urls.forEach(function (url) {
    console.log('begin');
    request = request(url)
        .get('')
        .expect(200)
        .end(function (err, res) {
            // Check for something
        });
    console.log('end');
});

When there is only 1 URL in the array, it works just fine. If I add a 2nd one, however, it fails with the output:

begin
end
begin

file.js:11
request = request(json)
^
TypeError: object is not a function

My guess is that I can't have 1 instance of supertest running twice, but I can't seem to find a solution to work around this. Any help is appreciated.


Solution

  • It is because your assignment request = request(url) overrides the request function.

    var urls = [
        "https://www.example.com",
        "https://www.example2.com"];
    
    urls.forEach(function (url) {
        console.log('begin');
        var r = request(url)
            .get('')
            .expect(200)
            .end(function (err, res) {
            // Check for something
        });
        console.log('end');
    });
    

    In the first iteration request is referring to a global function but when the request = request(url) statement is evaluated the value of request is changed as the value returned by request(url) so in the second iteration request is no longer the function you were expecting it to be.