Search code examples
javascripttypescriptasynchronousjestjssupertest

What is the correct way to await fs.readFile from another asynchronous function?


I'm using a combination of Jest and Supertest to test an API endpoint. I'm using the beforeAll() function of Jest to call the endpoint once before a collection of tests. Before I call the endpoint, I'm reading the request body from a file using fs.readFile.

Whatever I try, I cannot seem to await the result of my function that calls fs.readFile. My request is resulting in a 400 response every time, since the function readRequestBody is not being awaited. It seems that the program flow is continuing without awaiting the result and, therefore, sending an empty request body.

Code:

describe("Test POST call " + process.env.ENV, () => {
    const url = config.apiURL;
    let responseData: request.Response;

    beforeAll(async (done) => {
        const requestBody = await readRequestBody();
        responseData = await request(config.apiURL)
            .post("/v1.0/subjects/courses")
            .send(requestBody)
            .accept("application/vnd.api+json")
            .set("content-type", "application/vnd.api+json");
        done();
    });

    test("authorized should return 201 status code", () => {
        expect(responseData.status).toBe(201);
    });
});

async function readRequestBody() : Promise<string> {
    let requestBody: string = "";

    fs.readFile("./request.json", "utf8", (err, req) => {
        if (err) {
            console.log("Error loading request: " + err.message)
        }
        requestBody = req.replace("{{newCourseUuid}}", uuid.v4());
    });

    return requestBody;
}

I understand that fs.readFile reads the contents of a file asynchronously, but it looks like I'm not awaiting the results correctly. What am I missing? Is this something related to the fact that beforeAll is, itself, an asynchronous function?


Solution

  • try await fs.promises.readFile('file.txt') instead 👍

    https://nodejs.org/api/fs.html#fs_fs_promises_api