Search code examples
javascriptnode.jsfor-loopsupertest

Issue with object modified after supertest response inside nested for loops


My code looks like this:

let fs = require('fs');
let path = require('path');
let supertest = require('supertest');
let json = require('../../Util/json');
let chai = require('chai');
let assert = chai.assert;

let client = supertest("some_base_url");

describe('My test suite', function () {

    it('My sample test', () => {
        let results = {};
        fs.readdirSync("some_dir").forEach(dir => {
            fs.readdirSync("some_dir" + dir).forEach(file => {
                console.log(`Found file ${file} in directory ${dir}`);
                let json_file = "some_dir" + dir + path.sep + file;
                let data = fs.readFileSync(json_file, 'utf8');
                if (dir !== undefined) {
                    let url = dir + file.split('.')[0];
                    console.log("Request endpoint:", url);
                    client.get(url)
                        .set('Content-Type', 'application/json')
                        .expect(200)
                        .end(function (error, response) {
                            if (error) {
                                console.log("Error:", error);
                            } else {
                                data_obj = JSON.parse(data);
                                result_obj = JSON.parse(response.text);
                                results[dir + '-' + file] = json.assertJson(data_obj, result_obj); // assertJson results boolean value
                            }
                        });
                } else {
                    console.log(`Could not find any endpoint defined for ${dir}, skipping tests for the same.`);
                }
            });
        });
        console.log("Results:",JSON.stringify(results, null, 2));
        assert(!Object.values(results).includes(false));
    });
});

The problem is that the results object is empty when printed outside the outer for loop, but gives properly populated output when printed inside the for loop. In spite of the fact that my code is synchronous and there are no promises used, I wonder why this is happening.

EDIT: After doing some experiments (like commenting out the supertest code in my code and simply modifying the results object inside the for loop), I get expected output for results outside the for loops. So I believe there's something wrong with the way I'm using supertest. I intend to use it in a synchronous way.


Solution

  • I did not find any obvious ways to use supertest in a synchronous way, so I resolved the issue for myself by using sync-request.