Home > other >  how to run the rest of the test code after a failed call to the contract in hardhat?
how to run the rest of the test code after a failed call to the contract in hardhat?

Time:11-02

I'm trying to write a test for my smart contract in hardhat with js, I want to check somethings in case a call to my contract fails the problem is that when the line of "failed contract call" runs it reverts the whole block of test and will not run the rest of it. how can I make it work?

some code 1
await contract.function()
// contract call fails intentionally
some code 2

I need the result of "some code 2" but I just get an error that the call has failed.

CodePudding user response:

It's standard requirement for tests, just use chai and don't create your own test engine. https://www.chaijs.com/api/bdd/

CodePudding user response:

Assuming you're using the Hardhat Chai Matchers extension, you can validate function call revert with expect()

  • to.be.reverted
  • to.be.revertedWith()
  • to.be.revertedWithPanic()
  • to.be.revertedWithCustomError()
  • to.be.revertedWithoutReason()

Example:

it("fails to call the function", async () => {
    await expect(
        contract.function()
    ).to.be.revertedWith("Custom revert message");
});

Docs: https://hardhat.org/hardhat-chai-matchers/docs/overview#reverts

  • Related