2

I should be able to test my errors against AnchorError codes in my TS tests (Ref), but when I run my tests are not working as expected and unable to recognize the AnchorError.

Here's my snippet:

    const someInstruction = await program.methods.doSomething()
        .accounts({
            user: user.publicKey,
        })
        .instruction();

    const transaction = new Transaction()
        .add(computeInstruction)
        .add(someInstruction);

My assertions that aren't working even though the tx is throwing as expected.

    try {
      const signature = await anchor.web3.sendAndConfirmTransaction(program.provider.connection, transaction, [user]);
     } catch (_err) {
      assert.isTrue(_err instanceof AnchorError);
      const err: AnchorError = _err;
      const errMsg = "My Anchor Error";
      assert.strictEqual(err.error.errorMessage, errMsg);
    }

1 Answer 1

2

The issue is how I'm sending the transaction. Though, there is nothing wrong with how I'm sending my transaction, I'm was sending my transaction using the @solana/web3.js method, sendAndConfirmTransaction-- therefore the error type I'm getting back is a SendTransactionError.

If you want to use AnchorError in your testing, you will need to use Anchor's method for sending the transaction to the cluster, .rpc(), like so:

    try {
        await program.methods.doSomething()
        .accounts({
            user: user.publicKey,
        }).signers([user])
        .preInstructions([computeInstruction])
        .rpc();
    } catch (_err) {
      assert.isTrue(_err instanceof AnchorError);
      const err: AnchorError = _err;
      const errMsg = "My Anchor Error";
      assert.strictEqual(err.error.errorMessage, errMsg);
    }

Note that I am still able to append computeInstruction using the .preInstructions() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.