Search code examples
javascriptsolanasolana-web3jsanchor-solana

Error handling when testing Solana event emitting


I'm writing a test of event emitting in my Solana program as described here: https://github.com/coral-xyz/anchor/blob/master/tests/events/tests/events.js

anchor.setProvider(anchor.AnchorProvider.env());
const program = anchor.workspace.Events;

it("Is initialized!", async () => {
  let listener = null;

  let [event, slot] = await new Promise((resolve, _reject) => {
    listener = program.addEventListener("MyEvent", (event, slot) => {
      resolve([event, slot]);
    });
    program.rpc.initialize();
  });

  await program.removeEventListener(listener);

  assert.isAbove(slot, 0);
  assert.strictEqual(event.label, "hello");
});

It works good if the instruction completes successfully. But if any error happens during execution, the test code silently waits forever for event emitting which expectedly doesn't happen.

Can anyone please suggest a way to deal with such exceptions so that they are not "swallowed" and thrown on upper level?


Solution

  • If I understand the issue correctly, you need to add some sort of timeout when waiting for the event, correct? In that case, you should be able to use a setTimeout to check the result of your listener and error if it hasn't fired, ie:

    it("Is initialized!", async () => {
      let listener = null;
      let event = {label: ""};
      let slot = 0;
      setTimeout(function(){
        assert.isAbove(slot, 0);
        assert.strictEqual(event.label, "hello");
      },5000);
      [event, slot] = await new Promise((resolve, _reject) => {
        listener = program.addEventListener("MyEvent", (event, slot) => {
          resolve([event, slot]);
        });
        program.rpc.initialize();
      });
    
      await program.removeEventListener(listener);
    });