简体   繁体   English

如何监视由EventEmitter事件触发的回调调用中的sinon? Javascript,ES6,单元测试,Chai

[英]How to spy with sinon on callback calls triggered by EventEmitter events? Javascript, ES6, Unit-tests, Chai

I need to test whether my callback was called n number of times and always returned true. 我需要测试我的回调是否被调用过n次,并且始终返回true。
Here is my test callback function in typescript: 这是我在打字稿中的测试回调函数:

const checkBlockTransaction = (block: ILogsBlock) => {
  const tx = transactions.find(element => element.block === block.blockNumber);
  try {
    assert.strictEqual(block.transactions[0].amount, tx.amount);
  } catch (e) {
    return false;
  }
  return true;
};

here is my test which currently fails, because the spy doesn't register any function calls 这是我目前无法通过的测试,因为间谍没有注册任何函数调用

describe('Erc20DepositsWatcher', () => {
  it('handles blocks correctly', async () => {
    const spy = sinon.spy(checkBlockTransaction);
    for (const tx of transactions) {
      await deployedContract.methods.transfer(tx.address, tx.amount)
      .send({ from: addresses[0] });
    }

    depositsWatcher.subscribe(checkBlockTransaction);
    await depositsWatcher.startBroadcasting();
    await depositsWatcher.handleNewBlock(await web3.eth.getBlock('latest'));
    assert.equal(spy.callCount, 7);
    //sinon.assert.callCount(spy, 7);
    //assert(spy.alwaysReturned(true));
  });
});  

maybe there is a better solution than spying with sinon but I didn't find it yet 也许有比用sinon监视更好的解决方案,但我还没有找到

My current solution is without spies, but it's not very nice looking: 我当前的解决方案没有间谍,但是看起来不是很好:

function checkCallbackCalled(done: any, callsNumber: number) {
  let counter = 0;
  return (block: ILogsBlock) => {
    const tx = transactions.find(element => element.block === block.blockNumber);
    try {
      assert.strictEqual(block.transactions[0].amount, tx.amount);
    } catch (e) {
      done(e);
    }
    counter += 1;
    if (counter === callsNumber) done();
  };
}

describe('Erc20DepositsWatcher', () => {
  it('handles blocks correctly', async (done) => {
    for (const tx of transactions) {
      await deployedContract.methods.transfer(tx.address, tx.amount)
      .send({ from: addresses[0] });
    }

    depositsWatcher.subscribe(checkCallbackCalled(done, 7));
    await depositsWatcher.startBroadcasting();
    await depositsWatcher.handleNewBlock(await web3.eth.getBlock('latest'));
  });
});

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

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