简体   繁体   中英

How to test a generator function called using CO

This is a simplification of a real world scenario:

I have generator function called with three parameters.Two integers and a function. The third parameter function can add two integers.

//My add function
var fn = (a,b)=>a+b;

//My generator function
var genFn = function*(a,b,fn){
b = yield fn(a,b);
b = yield fn(a,b);
return b;
};

I have another function, which wraps the generator function using CO

//My wrapper function
var coGen = (a,b,fn)=>{ 
     co(genFn.bind(null,a,b,fn))
};

In my test case,I am interested in knowing how many times my function "fn" is called.

I tried to do this by using sinon Spy.

var spy =sinon.spy(fn);
coGen(1,2,spy);

When I do this and check callCount on the spy, it always returns 1. Though in reality, the spy is getting passed and called multiple times. When I check call count within my genFn function, it gives me the correct count.

I am sure, I am not testing it the right way. Can some one give me some idea on how to test? Thanks.

I was able to resolve it. It was a silly mistake. I don't think many will make this mistake.Just in case, if some one is interested. The way I tested was wrong. 'co' returns a promise. Looking for the callCount in the 'resolved' method of the promise will give the correct callCount of the spy.

var spy =sinon.spy(fn);
coGen(1,2,spy).then(()=>assert(spy.callCount===2));//true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM