3

I got two questions :

First :

I have some custom error type declared in the smart contract and I want to check the appropriate error to be returned from the function call , I wonder how can I get the response ?

For example :

#[msg("Username length should not exceed 100 characters")]
PhoneNumberLengthExceeded,

And I have this test :

        await program.methods.signUp("sajjad", "09146979106555555555", "").accounts({

        user: secondUser.publicKey,
        authority: provider.wallet.publicKey,
        systemProgram: SystemProgram.programId,
        clock: anchor.web3.SYSVAR_CLOCK_PUBKEY,

    }).signers([secondUser]).rpc({ skipPreflight: true });

which throws PhoneNumberLengthExceeded and messes up the test .

enter image description here

Second how can I write tests for the build in errors ?

which is thrown for example when the second user is being created with the first user Keypair which is obvious .

2 Answers 2

5

There are a few ways to assert errors. Here is one from Anchor's tic-tac-toe example:

try {
    await program.methods.signUp("sajjad", "09146979106555555555", "").accounts({
        user: secondUser.publicKey,
        authority: provider.wallet.publicKey,
        systemProgram: SystemProgram.programId,
        clock: anchor.web3.SYSVAR_CLOCK_PUBKEY,
    }).signers([secondUser]).rpc({ skipPreflight: true });
    
    // we use this to make sure we definitely throw an error
    chai.assert(false, "should've failed but didn't ")
} catch (err) {
    expect(err).to.be.instanceOf(AnchorError)
    expect((err as AnchorError).error.errorCode.number).to.equal(6000)
}

The errorCode.number is the ordinal value of your specific Errors enum or you can be explicit about it like this:

#[msg("Username length should not exceed 100 characters")]
PhoneNumberLengthExceeded = 6000,

You can also do an assertion on errorCode.message to match the one defined in the macro if you find that more developer-friendly.

2
try {
  await program.methods
    .signUp("sajjad", "09146979106555555555", "")
    .accounts({
        user: secondUser.publicKey,
        authority: provider.wallet.publicKey,
        systemProgram: SystemProgram.programId,
        clock: anchor.web3.SYSVAR_CLOCK_PUBKEY,

    }).signers([secondUser]).rpc({ skipPreflight: true });

} catch (_err) {
   // do anything with error message here
   console.log(_err);
}

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.