mercredi 3 janvier 2018

Best way to unit test promisified functions with Tape JS?

I'm writing unit tests for promisified code. What's the "right" way to go about unit testing async code like this? It seems like using timeouts and waiting some arbitrary amount of time for calls to go through is a bad idea for robust testing.

Below is some example code for the functions I want to write tests for. Thanks!

function getAllItems(){
return createRequest(URLS["a"],{}, itemsCB);
}

function itemsCB(response){
var items = JSON.parse(response).objects;
Items.append(items);
}

function createRequest(url, body, callback){
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function(){
        if(xhr.status == 200){
            if(callback != null){
                callback(xhr.responseText);
            }
            resolve(xhr.responseText);
        }
        else{
            reject(xhr.statusText);
        }
    }
    xhr.onerror = function() {
        reject(Error("Network Error"));
    };

    xhr.open("GET", url);
    xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    xhr.send('');
});

}

Aucun commentaire:

Enregistrer un commentaire