Why do we need deployments.fixture?

814 Views Asked by At

I have the following code below

const { deployments, ethers, getNamedAccounts } = require("hardhat")

describe("FundMe", async () => {
    beforeEach(async () => {
        const { deployer } = await getNamedAccounts()
        await deployments.fixture(["all"])
        fundMe = await ethers.getContract("FundMe")
        console.log(fundMe, "fundMe")
    })

    it("test", () => {})

    describe("constructor", async () => {})
})

I am running the mocks contract and the fundme contract before getting the fundme contract. However, I was wondering why we needed this? If these are my only two contracts it would work without deployments.fixture because it seems that hardhat runs all the contracts by default if no fixtures are specified?

I tried looking at the hardhat documentation.

2

There are 2 best solutions below

0
On

fixture is used in testing to create a proper test environment. for example, if you write a smart contract which uses or interacts with some ERC20 tokens, in order to deploy the contract, you have to deploy those contracts. Or maybe some contracts inherits from interface and you need to provide those interfaces. that is what fixture is used to provide all necessary data in order to use your smart contract

0
On

This medium article explains it quite simply.

By calling await deployments.fixture(['MyContract']) in your test, the same deployment is used for all tests, which eliminates the need to replicate the deployment procedure.

The MyContract (or the all in your example) reference a tag that is added in the deployment scripts. So all the deployment scripts that have the given tag (MyContract) are going to be deployed before the test and that exact deployment is going to be used for all tests.

For example, a deployment script with these tags:

module.exports.tag = ["all", "MyContract"]

will be deployed once if we do await deployments.fixture(['MyContract']) or await deployments.fixture(['all']) but will be deployed for each test if we do await deployments.fixture(['someOtherTag']) because it doesn't have that someOtherTag tag