Hardhat – Property ‘revertedWithCustomError’ Not Existing on Type ‘Assertion’

errorhardhattesttypescript

Im updating my project from Javascript to Typescript. Up until now I had no issues using revertedWithCustomError. When trying to assert with revertedWithCustomError I get the following linter error messaged Property 'revertedWithCustomError' does not exist on type 'Assertion'. I saw a similar issue in this post which says to use hardhat-toolbox, install it and import it which I have done.

The header imports in my TS look like:

const ethers = require("ethers");
import { loadFixture } from "@nomicfoundation/hardhat-network-helpers";
import { expect } from "chai";
import { BigNumber, constants } from "ethers";

Here is my tsconfig.json file:

{
  "compilerOptions": {
    "target": "es2020",
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "exclude": ["dist", "node_modules"],
  "include": ["./src", "./scripts"],
  "files": ["./hardhat.config.ts"]
}

Here is an example test snippet:

    it("Should validate list errors 721", async function () {
      const { Marketplace, New1155Nft, New721Nft } = await loadFixture(deployFixture);
      await expect(marketplace.connect(USER).listNFT(
        marketplace.address, 
        BigNumber.from(1), 
        ethers.utils.parseEther("1"), 
        TOMORROW, IN_FIVE_DAYS, 
        { value: listingFee}
      )).to.be.revertedWithCustomError(marketplace, "UnsupportedNftInterface");
  });

How do I resolve the error?

Best Answer

Ok I resolved this. The documentation in both their website and in the post I reference are off.

I created a new typescript project using npx hardhat and realized they import ethers through hardhat-chai-matchers. So I made these changes and my tests pass now:

// const ethers = require("ethers"); //Removed
import { loadFixture } from "@nomicfoundation/hardhat-network-helpers";
import "@nomicfoundation/hardhat-chai-matchers"; //Added for revertWithCustomErrors
import { expect } from "chai";
import { BigNumber, constants } from "ethers";
import hre from "hardhat";

// within test code using hre.ethers
await expect(marketplace.connect(USER).listNFT(
    marketplace.address, 
    hre.ethers.utils.parseEther("1"), 
    { value: listingFee}
)).to.be.revertedWithCustomError(marketplace, "UnsupportedNftInterface");

Alternatively I found you can do this import without hre like below though I am unsure of the correctness:

import { ethers } from "hardhat";

// within test code using ethers
await expect(marketplace.connect(USER).listNFT(
    marketplace.address, 
    ethers.utils.parseEther("1"), 
    { value: listingFee}
)).to.be.revertedWithCustomError(marketplace, "UnsupportedNftInterface");