samedi 6 octobre 2018

Asynchronous test function

I'm trying to create a function to testing asynchronous code, but I'm kind of lost, I want the TEST_F and TEST function below also work with asynchronous code, such as loading the image for example.

const CHECK = (actual, expected) => {
    return (actual === expected);
};

const TEST = (name, ...testFunctions) => {
    console.log(name+':');
    for (let test of testFunctions)
        console.log(test);
};

const TEST_F = (name, f) => {
    const tStart = performance.now();

    const check = f();

    const tEnd = performance.now();
    const duration = tEnd - tStart;

    const details = name + ': ' + '(' + duration + ') = ' + check;

    return details;
};

const imageDownload = (path, successCallback) => {
    let img = new Image();

    img.addEventListener("load", successCallback, false);

    img.src = path;

    return img;
};

TEST("TestImage", 
    TEST_F("testImageDownload", () => {
        let spyCountSuccess = 0;
        const expectedCountSuccess = spyCountSuccess + 1;

        const successCallback = () => {
            spyCountSuccess++;
        };
        const pathImage = 'https://imgur.com/a/IglYdx8';
        imageDownload(pathImage, successCallback);

        const actualCountSuccess = spyCountSuccess;

        return CHECK(actualCountSuccess, expectedCountSuccess);
    })

);

With the code above I will always i get false, even if the image is loaded, because I am not dealing right with the concept of asynchronous, I would like to understand how to adapt the code thus to also test ascincrono code.

Aucun commentaire:

Enregistrer un commentaire