Cadence Testing Guide
Write and run unit tests for Cadence smart contracts using the built-in Test contract and the Flow CLI's flow test command. Tests are Cadence files named *_test.cdc that run against an implicit in-process emulator. They deploy contracts, execute scripts and transactions, and assert expected behavior — all through calls on the Test contract.
Key Principles
- Lifecycle is fixed —
setup()runs once,beforeEach()/afterEach()wrap every test,testXxx()functions are the test cases, andtearDown()runs once at the end. All are optional except the test functions. - Start each test from a clean state — deploy contracts in
setup(), capture the height, and callTest.reset(to: setupHeight)inbeforeEach()to rewind to that snapshot. - Use the right assertion —
Test.assert(cond, msg?)for boolean checks,Test.assertEqual(expected, actual)for equality,Test.expect(value, matcher)for matcher-based checks, andTest.expectFailure(closure, errorSubstring)for expected failures. - Cover failure paths — access-control denials, pre/post-condition violations, and resource-ownership errors are the parts of the contract that bugs hide in. Every test file should include at least one
expectFailurecase.
Navigation
| Task | Reference |
|---|---|
Project layout, flow.json test aliases, lifecycle, first test |
setup-and-basics.md |
Assertions, matchers, combinators, custom matchers, expectFailure |
assertions-and-matchers.md |
Accounts, deployments, scripts, transactions, reset, moveTime, mocking |
blockchain-emulation.md |
| Events and logs — reading, filtering, asserting | events-and-logs.md |
| Running tests, coverage, determinism, fork mode, CI | coverage-and-ci.md |
| Testing patterns, isolation, flakiness prevention, anti-patterns | patterns.md |
Running Tests — Quick Reference
flow test # run every *_test.cdc it can find
flow test cadence/tests/Counter_test.cdc # run a specific file
flow test --cover # with coverage report
flow test --name testMintWorks # only tests whose name matches
flow test --seed 42 # deterministic random order
Full flag reference and CI integration live in coverage-and-ci.md.
Companion Skills
cadence-lang— Essential. Tests are Cadence too; all access control, resource, and capability rules apply.cadence-scaffold— Generate the contracts and transactions you're about to test.cadence-audit— After writing tests, audit the contracts they cover. Audit findings often point back at missing tests.flow-cli— Background on non-test CLI commands. This skill coversflow testin depth.flow-project-setup— Configuringflow.jsonoutside a testing context.