In this tutorial, you'll learn how to use Foundry's 'cheatcodes'—special commands that allow you to test and manipulate blockchain states. We'll focus on the `vm.expectEmit` cheatcode to test events.
If the output contains text similar to command not found, please install that item.
Get started
Set up project
To follow along, start with the main branch, which is the default branch of this repository. This gives you the initial state from which you can follow along with the steps as described in the tutorial.
forge manages dependencies by using git submodules. Clone the following project and pass --recurse-submodules to the git clone command to automatically initialize and update the submodule in the repository.
Open the project test-an-event-with-foundry, in a code editor.
If you completed the previous tutorial, you may notice the contents of the contract TodoList.sol have changed. Specifcally, there is a CreateTodo event that has been declared and is emitted in the createTodo() function.
Write the test
An almost-complete test has already been prepared for you. It's located at test/TodoList.t.sol. You will only need to make a few modifications (outlined below) for it to run successfully.
Look for a comment in the code to locate the specific lines of code which you will need to edit. For example, in this step, look for this: // Step (1) in the accompanying tutorial You will need to delete the inline comment that looks like this: /* ... */. Replace it with the correct code.
Step 1: Define the expected event
Declare the CreateTodo event in your test contract. This event is identical to the one that is declared in TodoList.sol.
The cheatcode vm.expectEmit() will be used to check if the event is emitted. This cheatcode expects four inputs:
bool checkTopic1 asserts the first index
bool checkTopic2 asserts the second index
bool checkTopic3 asserts the data for index 3
bool checkData asserts the remaining data emitted by the event
address emitter asserts the emitting address matches
The event being tested includes two indexed arguments: address indexed creator and uint256 indexed todoIndex. Therefore, we want to assert the matching of topic 1, topic 2, the non-indexed data, and the emitting address with our actual event.