samedi 30 janvier 2016

Unit testing asynchronous function which connects to database

Well I have some functions which connect to database (redis) and return some data, those functions usually are based on promises but are asynchronous and contain streams. I looked and read some things about testing and I chose to go with tape, sinon and proxyquire, if I mock this function how I would know that it works?

The following function (listKeys) returns (through promise) all the keys that exist in the redis db after completes the scanning.

let methods = {
    client: client,
    // Cache for listKeys
    cacheKeys: [],
    // Increment and return through promise all keys
    // store to cacheKeys;
    listKeys: blob => {
        return new Promise((resolve, reject) => {
            blob = blob ? blob : '*';

            let stream = methods.client.scanStream({
                match: blob,
                count: 10,
            })

            stream.on('data', keys => {
                for (var i = 0; i < keys.length; i++) {
                    if (methods.cacheKeys.indexOf(keys[i]) === -1) {
                        methods.cacheKeys.push(keys[i])
                    }
                }
            })

            stream.on('end', () => {
                resolve(methods.cacheKeys)
            })

            stream.on('error', reject)
        })
    }
}

So how do you test a function like that?

Aucun commentaire:

Enregistrer un commentaire