How to test smart contracts with ethers.js and Truffle?

Jan 22, 2026Leave a message

Hey there! As an ethers supplier, I've seen firsthand how crucial it is to test smart contracts properly. In this blog post, I'm gonna walk you through how to test smart contracts using ethers.js and Truffle. It might sound a bit technical, but I'll break it down into easy-to-understand steps.

Why Testing Smart Contracts Matters

Before we dive into the testing process, let's quickly talk about why testing smart contracts is so important. Smart contracts are self - executing contracts with the terms of the agreement directly written into code. Once deployed on the blockchain, they're immutable, which means you can't change them easily. If there are bugs or vulnerabilities in your smart contract, it could lead to serious issues, like financial losses or security breaches. So, testing is like a safety net to catch those problems before they cause any real damage.

EINECS-203-905-0Dibutyl Carbitol

Prerequisites

To follow along with this guide, you'll need a few things:

  1. Node.js and npm: These are used to manage your project dependencies. You can download them from the official Node.js website.
  2. Truffle: It's a popular development framework for Ethereum. You can install it globally using npm install -g truffle.
  3. ethers.js: A lightweight library for interacting with the Ethereum blockchain. You can add it to your project using npm install ethers.

Setting Up a Truffle Project

First things first, let's create a new Truffle project. Open your terminal and run the following command:

truffle init

This will create a new directory with the basic structure of a Truffle project. You'll see folders like contracts, migrations, and test. The contracts folder is where you'll put your smart contract code, the migrations folder is for scripts to deploy your contracts, and the test folder is where we'll write our test cases.

Writing a Simple Smart Contract

Let's write a simple smart contract to test. Create a new file in the contracts folder called SimpleStorage.sol. Here's the code:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private storedData;

    function set(uint256 x) public {
        storedData = x;
    }

    function get() public view returns (uint256) {
        return storedData;
    }
}

This is a basic contract that allows you to store and retrieve a single unsigned integer.

Configuring Truffle

Next, we need to configure Truffle to work with our local development environment. Open the truffle-config.js file in the root of your project. You can set up a development network like this:

module.exports = {
    networks: {
        development: {
            host: "127.0.0.1",
            port: 8545,
            network_id: "*"
        }
    },
    compilers: {
        solc: {
            version: "0.8.0"
        }
    }
};

This configures Truffle to connect to a local Ethereum node running on localhost at port 8545.

Writing Tests with ethers.js and Truffle

Now, let's write some tests for our SimpleStorage contract using ethers.js. Create a new file in the test folder called SimpleStorage.test.js. Here's the code:

const { ethers } = require('ethers');
const { expect } = require('chai');

describe('SimpleStorage', function () {
    let simpleStorage;
    let provider;
    let signer;

    before(async function () {
        provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545');
        signer = provider.getSigner();

        const SimpleStorage = await ethers.getContractFactory('SimpleStorage', signer);
        simpleStorage = await SimpleStorage.deploy();
        await simpleStorage.deployed();
    });

    it('should set and get the value correctly', async function () {
        const valueToSet = 42;
        await simpleStorage.set(valueToSet);
        const retrievedValue = await simpleStorage.get();
        expect(retrievedValue.toNumber()).to.equal(valueToSet);
    });
});

In this test, we first set up a provider and a signer using ethers.js. Then we deploy our SimpleStorage contract. The it block is where we actually write our test case. We set a value in the contract and then retrieve it, and use the chai library to assert that the retrieved value is the same as the one we set.

Running the Tests

To run the tests, simply run the following command in your terminal:

truffle test

Truffle will compile your contracts, deploy them to the local network, and run all the test cases in the test folder. If everything goes well, you should see a message saying that all tests have passed.

Advanced Testing Concepts

Testing Events

Smart contracts can emit events, which are useful for notifying external applications about certain actions. Let's add an event to our SimpleStorage contract and write a test for it.

First, update the SimpleStorage.sol contract:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private storedData;
    event ValueSet(uint256 newValue);

    function set(uint256 x) public {
        storedData = x;
        emit ValueSet(x);
    }

    function get() public view returns (uint256) {
        return storedData;
    }
}

Now, update the SimpleStorage.test.js file to test the event:

const { ethers } = require('ethers');
const { expect } = require('chai');

describe('SimpleStorage', function () {
    let simpleStorage;
    let provider;
    let signer;

    before(async function () {
        provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545');
        signer = provider.getSigner();

        const SimpleStorage = await ethers.getContractFactory('SimpleStorage', signer);
        simpleStorage = await SimpleStorage.deploy();
        await simpleStorage.deployed();
    });

    it('should set and get the value correctly', async function () {
        const valueToSet = 42;
        await simpleStorage.set(valueToSet);
        const retrievedValue = await simpleStorage.get();
        expect(retrievedValue.toNumber()).to.equal(valueToSet);
    });

    it('should emit the ValueSet event', async function () {
        const valueToSet = 100;
        const tx = await simpleStorage.set(valueToSet);
        const receipt = await tx.wait();
        const event = receipt.events.find(event => event.event === 'ValueSet');
        expect(event.args.newValue.toNumber()).to.equal(valueToSet);
    });
});

In this new test case, we send a transaction to set a value in the contract. Then we wait for the transaction to be mined and get the receipt. We search for the ValueSet event in the receipt and assert that the value in the event is the same as the one we set.

Conclusion

Testing smart contracts with ethers.js and Truffle is a powerful way to ensure the reliability and security of your contracts. By following the steps in this guide, you can write comprehensive test suites for your smart contracts and catch any potential issues early on.

If you're in the market for high - quality ethers for your blockchain projects, we've got you covered. We offer a wide range of ethers, including Diethylene Glycol Dibutyl Ether CAS 112-73-2, METHYL PERFLUOROBUTYL ETHER CAS 163702-08-7, and 2-Butoxyethanol CAS 111-76-2. If you're interested in learning more or discussing a potential purchase, feel free to reach out and start a procurement conversation.

References

  • Truffle Documentation
  • ethers.js Documentation
  • Solidity Documentation

Send Inquiry

Home

Phone

E-mail

Inquiry