Question

Suppose you have the following JS function:

function YourProxy($orm, $usr) {

     this.addToDB = function(obj) {
     /* Do some validation on obj */
        return function(callback){
            var oo = $orm.createNew(obj);
            oo.save(options, function(err,ok){
                if(err) callback(err);
                callback(null,ok);
            }
        }
     }
}

which you can use on node.js with ES6 generators to wait for that operation to happen with something like:

function *(){
    var yourProxy = new YourProxy();
    try {
        var result = yield yourProxy.addToDB(anObject);
    } catch(e) { 
        /* Something went wrong sync. Here you have err from save's callback */
    }
    /* result contains ok, the one from save's callback */
}

To test that I've done something like this, using mocha and sinon (and mocha-sinon):

describe('addToDB', function(){
    it('adds the object to the db', function(){
        var callback = sinon.spy();
        myProxy.addToDB(anObject)(callback);
        expect( callback ).to.be.calledOnce;
    });
 });

but all I got is that the callback is never called because addToDB() exits before the save's callback gets called.

How would you test that?

Was it helpful?

Solution

Try using co-mocha and yield the generator as you did it in your example.

describe('addToDB', function(){
    it('adds the object to the db', function* (){
        var callback = sinon.spy();
        yield myProxy.addToDB(anObject)(callback);
        expect( callback ).to.be.calledOnce;
    });
 });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top