Testing the nodejs harmonic generator method

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 in node.js with ES6 generators to wait for this 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 callback */
    }
    /* result contains ok, the one from save callback */
}

To verify that I did something similar using mocha and sine (and mocha-sine):

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 callback is never called because addToDB () exits before calling the save call.

How would you test this?

+4
source share
1 answer

Try using co-mochaand type a generator, as you did 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;
    });
 });
+3
source

Source: https://habr.com/ru/post/1530628/


All Articles