简体   繁体   English

如何测试使用CO调用的生成器功能

[英]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 我还有另一个函数,它使用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. 在我的测试案例中,我想知道我的函数“ fn”被调用了多少次。

I tried to do this by using sinon Spy. 我试图通过使用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. 当我执行此操作并检查间谍程序的callCount时,它始终返回1。尽管实际上,间谍程序被传递并多次调用。 When I check call count within my genFn function, it gives me the correct count. 当我在genFn函数中检查呼叫计数时,它将为我提供正确的计数。

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. “ co”返回一个承诺。 Looking for the callCount in the 'resolved' method of the promise will give the correct callCount of the spy. 在promise的“ resolved”方法中查找callCount会为间谍提供正确的callCount。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用chai在redux-sagas生成器功能测试用例中测试catch块? - How to test catch block in redux-sagas generator function test cases using chai? 如何与生成器一起使用co.wrap - how to use co.wrap with generator 如何使用 Cypress 对在 React 组件上调用的回调函数进行单元测试 - How to unit test a callback function was called on a React component using Cypress 如何测试使用middy时调用的处理程序function - how to test that handler function is called when using middy 如何测试是否在异步调用的测试函数B中调用了函数A - How to test if function A was called inside the test function B if it was called asynchronously 如何从生成器函数调用的异步回调中产生收益? - How to yield from an async callback called from a generator function? 从生成器函数中包装co和co-mysql,并从包装函数中退出 - wrapping co and co-mysql from within a generator function, and yielding out of the wrapping function 如何在NodeJS中测试递归调用的函数? - How to test a recursively called function in NodeJS? 如何测试一个函数在另一个函数之前调用 - How to test that one function is called before another 如何测试函数在react jest中被调用? - How to test a function is called in react jest?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM