I'm trying to unit test my simple contract however, I don't know which way to do it.

For unit-testing should I create a new contract on beforeEach(), so it runs before each it()? Using: new ethers.Contract()
Or should I interact with my hardhat already deployed contract with: getContractAt() or getContract()?


describe("testing title", async () => {
  let signers, TDM
  beforeEach(async () => {
    signers = ethers.getSigners()

    TDMContract = await ethers.getContractAt(
    TDM = TDMContract.connect(signers[1])

  it("constructor", async () => {
    const name = await TDM.name()
    assert.equal(name, "TokenDistrubutionMechanism")

1 Answer 1


Both approaches are needed.

When it comes to testing, the more you have tests and the better it is.

For unit testing, you should create a new instance of your contract within the beforeEach function to deploy a new contract before each test.

On the other hand, scenario testing involves testing the behavior of your contract in real scenarios where it interacts with other contracts, requires previous actions, relies on different actions, or external contracts.

For both unit and scenario testing, you can deploy using:

await ethers.getContractFactory("CONTRACTNAME");

In summary, unit tests focus on testing individual functions or units of your code (deploy beforeEach test case), while scenario tests focus on testing the behavior of your code in real-world scenarios (deployed once)

  • Thanks! Can you explain when do you use the getContract() method?
    – IBeFrogs
    Apr 1 at 12:58
  • I'm not sure the getContract method exists. I tried, and I got this error: TypeError: ethers.getContract is not a function
    – Adam Boudj
    Apr 1 at 13:12
  • I think it got updated to getContractAt()
    – IBeFrogs
    Apr 1 at 13:21
  • getContractAt is to connect to an existing contract (deployed already). You don't thing you need to use it on tests except if you fork an existing network (e.g, Ethereum), and you want to connect to an existing contract.
    – Adam Boudj
    Apr 1 at 13:25

Your Answer

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

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