Nesting Fixtures in Ethereum-Waffle
Test fixtures are a great way to save time in a smart contract test suite.
Instead of recreating the entire chain state on each test, you can essentially snapshot your chain position, so every time you run a new test case, it starts at the snapshotted state.
One problem, though. As DeFi gets more complex, we're going to begin calling more and more test fixtures in our contract tests. I'm working on a staking library right now, and that relies on several layers of fixtures.
I spent some time this week trying to figure out how the fixtures do work. Turns out, it's actually very simple:
Ok, so what's going on here? createFixtureLoader is a factory that returns a loadFixture function, bound to a set of wallets and a provider.
The real magic is with the evm_revert and evm_snapshot calls.
So if you want to nest fixtures, you have to call them a specific way:
- Outermost fixture is loaded with loadFixture(outermostFixture)
- Inner fixtures are then loaded the way that they get called in loadFixture: fixture(wallets, provider).
That way, it only snapshots once.