lundi 4 novembre 2019

Jest 'expect' evaluates before function returns a result

I'm testing JS (Node) code that formats data into a CSV-string, using Jest. The test just counts the lines in the returned CSV string, and tests this value against the expected amount of lines. The function counting the lines is a synchronous function, that returns the amount of lines. However, the testcase (expect(amount).toBe(lines);) evaluates before the counter function returns its value, resulting in this kind of output : Expected: 55, Received: 0. The line at the end of the countCSVLines() function prints the right amount, but only after the test completes.

I am aware of Jest's possibilities for awaiting async code (as explained here), but as far a I am aware, this is not an asynchronous function, so I should not need these statements. I have, however, tried writing the function so that it returns a promise and awaiting that, but that also did not work.

describe ("Test", () => {

    it("Should generate a CSV file of all registrations", async () => {
        const amount = 55
        const csv = await getCSV(); ... //get csv etc
        const lines = countCSVLines(csv);
        expect(amount).toBe(lines);
    });

    function countCSVLines(csvFile) {
        let lineCounter = 0;
        let location = 0;
        do {
            location = csvFile.search("\n");
            //substring from start until just behind found '\n'
            lineCounter++;
            csvFile = csvFile.substring(location + "\n".length);
        } while (location !== -1);

        console.log(`Returning lineCounter: ${lineCounter}`);
        return lineCounter;
    }
});

I expect Jest to wait until this function returns its result and evaluate the 'expect' after and pass the test, but it keeps failing.

What am I missing here?

Aucun commentaire:

Enregistrer un commentaire