0
0
Blockchain / Solidityprogramming~30 mins

Event testing in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Event Testing in Blockchain Smart Contracts
📖 Scenario: You are building a simple blockchain smart contract that tracks product sales. Each time a product is sold, the contract emits an event with the product name and price. You want to test that this event is emitted correctly when a sale happens.
🎯 Goal: Create a smart contract that emits a ProductSold event when a product is sold. Then write a test script to check that the event is emitted with the correct data.
📋 What You'll Learn
Create a Solidity smart contract with a ProductSold event
Add a sellProduct function that emits the event with product name and price
Write a JavaScript test using Hardhat or similar framework to call sellProduct
Verify the ProductSold event is emitted with the expected product name and price
💡 Why This Matters
🌍 Real World
Events in blockchain smart contracts are like notifications that something important happened. They help users and other programs know when actions occur, such as a product sale or token transfer.
💼 Career
Blockchain developers must write and test events to ensure smart contracts communicate correctly with users and other systems. Event testing is a key skill for building reliable decentralized applications.
Progress0 / 4 steps
1
Create the Solidity contract with the ProductSold event
Create a Solidity contract called Store. Inside it, declare an event called ProductSold that takes a string productName and a uint price. Also add a public function called sellProduct that takes string memory productName and uint price as parameters but leave the function body empty for now.
Blockchain / Solidity
Need a hint?

Remember to use event keyword to declare events in Solidity.

2
Emit the ProductSold event inside sellProduct
Inside the sellProduct function, emit the ProductSold event with the productName and price parameters.
Blockchain / Solidity
Need a hint?

Use the emit keyword followed by the event name and parameters.

3
Write a JavaScript test to call sellProduct and check the event
Create a JavaScript test file. Import the contract factory and deploy the Store contract. Call the sellProduct function with "Laptop" and 1500. Use expect with to.emit to check that the ProductSold event is emitted with "Laptop" and 1500.
Blockchain / Solidity
Need a hint?

Use Hardhat's expect and to.emit syntax to test events.

4
Run the test and print success message
Add a console.log statement after the test call to print "Event test passed!" if the event is emitted correctly.
Blockchain / Solidity
Need a hint?

Use console.log("Event test passed!") to print the message.