Web3.js and Ethers.js Integration Testing: A Practical Guide

Web3.js and Ethers.js Integration Testing: A Practical Guide

Unit tests verify that your Solidity logic is correct in isolation. Integration tests verify that your JavaScript application correctly speaks to those contracts—and that all the pieces work together when the contracts interact with each other.

Integration testing at the Web3 layer is where most dApp bugs live. The contract compiles fine. The unit tests pass. But the front-end or backend service sends the wrong argument type, mishandles a BigNumber, ignores a failed transaction, or doesn't wait for enough confirmations. Integration tests catch these problems before users do.

This guide covers integration testing with both Ethers.js v6 (the current standard) and Web3.js v4, using Hardhat's local network as the test environment.

The Integration Testing Stack

Your app code (JavaScript/TypeScript)
        ↕
  Ethers.js / Web3.js
        ↕
  JSON-RPC Provider
        ↕
  Hardhat Network (local) or Ganache
        ↕
  Deployed Smart Contracts

Integration tests interact with deployed contracts through the same libraries your production code uses. Unlike unit tests that test Solidity in isolation, integration tests run your full JavaScript service against real contract state.

Project Setup

mkdir dapp-integration-tests && cd dapp-integration-tests
npm init -y
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox
npm install ethers web3
npx hardhat init

The key is running Hardhat Network as a persistent local node:

# Terminal 1: start the local node
npx hardhat node

# Terminal 2: deploy and run tests
npx hardhat run scripts/deploy.js --network localhost
npx hardhat test --network localhost

Or use Hardhat in-process (faster, no separate terminal):

// hardhat.config.js
module.exports = {
  networks: {
    hardhat: {
      chainId: 31337,
    },
    localhost: {
      url: "http://127.0.0.1:8545",
      chainId: 31337,
    }
  }
};

Contracts for Integration Testing

We'll use a simple token staking system with two interacting contracts:

// contracts/RewardToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract RewardToken is ERC20, Ownable {
    constructor(address owner) ERC20("Reward Token", "RWD") Ownable(owner) {
        _mint(owner, 1_000_000 * 1e18);
    }

    function mint(address to, uint256 amount) external onlyOwner {
        _mint(to, amount);
    }
}
// contracts/StakingPool.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract StakingPool {
    using SafeERC20 for IERC20;

    IERC20 public immutable stakeToken;
    IERC20 public immutable rewardToken;
    address public owner;

    uint256 public rewardRate = 100; // tokens per block per staker
    uint256 public totalStaked;

    struct StakeInfo {
        uint256 amount;
        uint256 startBlock;
        uint256 pendingRewards;
    }

    mapping(address => StakeInfo) public stakes;

    event Staked(address indexed user, uint256 amount);
    event Unstaked(address indexed user, uint256 amount, uint256 rewards);
    event RewardsClaimed(address indexed user, uint256 amount);

    error NothingStaked();
    error InsufficientBalance(uint256 available, uint256 requested);

    constructor(address _stakeToken, address _rewardToken) {
        stakeToken = IERC20(_stakeToken);
        rewardToken = IERC20(_rewardToken);
        owner = msg.sender;
    }

    function stake(uint256 amount) external {
        stakeToken.safeTransferFrom(msg.sender, address(this), amount);
        stakes[msg.sender].amount += amount;
        stakes[msg.sender].startBlock = block.number;
        totalStaked += amount;
        emit Staked(msg.sender, amount);
    }

    function pendingRewards(address user) public view returns (uint256) {
        StakeInfo storage info = stakes[user];
        if (info.amount == 0) return 0;
        uint256 blocksElapsed = block.number - info.startBlock;
        return info.pendingRewards + (blocksElapsed * rewardRate * info.amount) / 1e18;
    }

    function unstake(uint256 amount) external {
        StakeInfo storage info = stakes[msg.sender];
        if (info.amount == 0) revert NothingStaked();
        if (amount > info.amount) revert InsufficientBalance(info.amount, amount);

        uint256 rewards = pendingRewards(msg.sender);
        info.amount -= amount;
        info.pendingRewards = 0;
        info.startBlock = block.number;
        totalStaked -= amount;

        stakeToken.safeTransfer(msg.sender, amount);
        if (rewards > 0) {
            rewardToken.safeTransfer(msg.sender, rewards);
        }

        emit Unstaked(msg.sender, amount, rewards);
    }
}

Integration Tests with Ethers.js v6

// test/integration/staking.integration.test.js
const { expect } = require("chai");
const { ethers } = require("hardhat");
const { mine, loadFixture } = require("@nomicfoundation/hardhat-toolbox/network-helpers");

describe("StakingPool Integration Tests", function () {
  async function deployAllContracts() {
    const [owner, alice, bob] = await ethers.getSigners();

    // Deploy tokens
    const RewardToken = await ethers.getContractFactory("RewardToken");
    const rewardToken = await RewardToken.deploy(owner.address);

    // Use reward token as stake token for simplicity
    const stakeToken = rewardToken;

    const StakingPool = await ethers.getContractFactory("StakingPool");
    const pool = await StakingPool.deploy(
      await stakeToken.getAddress(),
      await rewardToken.getAddress()
    );

    // Fund pool with rewards
    await rewardToken.connect(owner).transfer(
      await pool.getAddress(),
      ethers.parseEther("100000")
    );

    // Give Alice and Bob some tokens to stake
    const stakeAmount = ethers.parseEther("1000");
    await rewardToken.connect(owner).transfer(alice.address, stakeAmount * 2n);
    await rewardToken.connect(owner).transfer(bob.address, stakeAmount * 2n);

    return { pool, stakeToken, rewardToken, owner, alice, bob, stakeAmount };
  }

  describe("Full stake-and-unstake lifecycle", function () {
    it("alice stakes, waits for blocks, unstakes with rewards", async function () {
      const { pool, stakeToken, alice, stakeAmount } = await loadFixture(deployAllContracts);
      const poolAddress = await pool.getAddress();

      // Step 1: Approve and stake
      await stakeToken.connect(alice).approve(poolAddress, stakeAmount);
      const stakeTx = await pool.connect(alice).stake(stakeAmount);
      await stakeTx.wait();

      // Verify stake recorded
      const stakeInfo = await pool.stakes(alice.address);
      expect(stakeInfo.amount).to.equal(stakeAmount);

      // Step 2: Mine some blocks to accumulate rewards
      await mine(10);

      // Step 3: Check pending rewards
      const pending = await pool.pendingRewards(alice.address);
      expect(pending).to.be.greaterThan(0n);

      // Step 4: Unstake and verify balances changed
      const aliceBalanceBefore = await stakeToken.balanceOf(alice.address);
      const unstakeTx = await pool.connect(alice).unstake(stakeAmount);
      const receipt = await unstakeTx.wait();
      const aliceBalanceAfter = await stakeToken.balanceOf(alice.address);

      // Balance should increase by at least the staked amount
      expect(aliceBalanceAfter).to.be.greaterThan(aliceBalanceBefore);

      // Verify event was emitted with correct data
      const unstakeEvent = receipt.logs.find(log => {
        try {
          return pool.interface.parseLog(log)?.name === "Unstaked";
        } catch { return false; }
      });
      expect(unstakeEvent).to.not.be.undefined;
    });
  });

  describe("Multi-user interactions", function () {
    it("multiple users can stake simultaneously without interfering", async function () {
      const { pool, stakeToken, alice, bob, stakeAmount } = await loadFixture(deployAllContracts);
      const poolAddress = await pool.getAddress();

      // Both stake
      await stakeToken.connect(alice).approve(poolAddress, stakeAmount);
      await stakeToken.connect(bob).approve(poolAddress, stakeAmount);
      await pool.connect(alice).stake(stakeAmount);
      await pool.connect(bob).stake(stakeAmount);

      // Total staked should be sum of both
      expect(await pool.totalStaked()).to.equal(stakeAmount * 2n);

      // Mine blocks
      await mine(5);

      // Alice unstakes — should not affect Bob's stake
      await pool.connect(alice).unstake(stakeAmount);
      expect(await pool.totalStaked()).to.equal(stakeAmount);

      const bobInfo = await pool.stakes(bob.address);
      expect(bobInfo.amount).to.equal(stakeAmount);
    });
  });

  describe("Transaction receipt inspection", function () {
    it("correctly parses Staked event from transaction logs", async function () {
      const { pool, stakeToken, alice, stakeAmount } = await loadFixture(deployAllContracts);

      await stakeToken.connect(alice).approve(await pool.getAddress(), stakeAmount);
      const tx = await pool.connect(alice).stake(stakeAmount);
      const receipt = await tx.wait();

      // Parse events from receipt
      const stakedEvents = receipt.logs
        .map(log => {
          try { return pool.interface.parseLog(log); }
          catch { return null; }
        })
        .filter(e => e?.name === "Staked");

      expect(stakedEvents).to.have.length(1);
      expect(stakedEvents[0].args.user).to.equal(alice.address);
      expect(stakedEvents[0].args.amount).to.equal(stakeAmount);
    });
  });
});

Integration Testing with Web3.js v4

Web3.js has a different API style but tests the same contract behaviors:

// test/integration/staking.web3.test.js
const { Web3 } = require("web3");
const { expect } = require("chai");
const { artifacts } = require("hardhat");

describe("StakingPool Integration Tests (Web3.js)", function () {
  let web3;
  let pool, stakeToken;
  let accounts;

  before(async function () {
    // Connect to Hardhat's local node
    web3 = new Web3("http://127.0.0.1:8545");
    accounts = await web3.eth.getAccounts();

    // Load compiled artifacts
    const StakingPoolArtifact = await artifacts.readArtifact("StakingPool");
    const RewardTokenArtifact = await artifacts.readArtifact("RewardToken");

    // Deploy RewardToken
    const RewardToken = new web3.eth.Contract(RewardTokenArtifact.abi);
    stakeToken = await RewardToken.deploy({
      data: RewardTokenArtifact.bytecode,
      arguments: [accounts[0]],
    }).send({ from: accounts[0], gas: 3_000_000 });

    // Deploy StakingPool
    const StakingPoolContract = new web3.eth.Contract(StakingPoolArtifact.abi);
    pool = await StakingPoolContract.deploy({
      data: StakingPoolArtifact.bytecode,
      arguments: [stakeToken.options.address, stakeToken.options.address],
    }).send({ from: accounts[0], gas: 3_000_000 });

    // Fund pool and users
    const amount = web3.utils.toWei("100000", "ether");
    await stakeToken.methods.transfer(pool.options.address, amount).send({ from: accounts[0] });
    await stakeToken.methods.transfer(accounts[1], web3.utils.toWei("5000", "ether")).send({ from: accounts[0] });
  });

  it("reads contract state correctly", async function () {
    const totalStaked = await pool.methods.totalStaked().call();
    expect(totalStaked).to.equal("0");

    const rewardRate = await pool.methods.rewardRate().call();
    expect(rewardRate).to.equal("100");
  });

  it("stake transaction succeeds and updates state", async function () {
    const alice = accounts[1];
    const stakeAmount = web3.utils.toWei("500", "ether");

    await stakeToken.methods
      .approve(pool.options.address, stakeAmount)
      .send({ from: alice, gas: 100_000 });

    const receipt = await pool.methods
      .stake(stakeAmount)
      .send({ from: alice, gas: 200_000 });

    // Check event in receipt
    expect(receipt.events.Staked).to.not.be.undefined;
    expect(receipt.events.Staked.returnValues.user.toLowerCase())
      .to.equal(alice.toLowerCase());
    expect(receipt.events.Staked.returnValues.amount).to.equal(stakeAmount);

    // Verify state
    const stakeInfo = await pool.methods.stakes(alice).call();
    expect(stakeInfo.amount).to.equal(stakeAmount);
  });

  it("handles BigInt arithmetic correctly", async function () {
    const alice = accounts[1];
    const balance = BigInt(await stakeToken.methods.balanceOf(alice).call());
    const stakeInfo = await pool.methods.stakes(alice).call();
    const staked = BigInt(stakeInfo.amount);

    // Web3.js v4 returns bigint natively
    expect(typeof balance).to.equal("bigint");
    expect(balance + staked).to.be.greaterThan(0n);
  });
});

Testing Event Listeners

Events are the primary way DApps receive updates. Test that your event handling code works correctly:

// test/integration/events.test.js
describe("Event listener integration", function () {
  it("receives Staked event via subscription", async function () {
    const { pool, stakeToken, alice, stakeAmount } = await loadFixture(deployAllContracts);

    const receivedEvents = [];

    // Set up listener BEFORE the transaction
    const filter = pool.filters.Staked(alice.address);
    pool.on(filter, (user, amount, event) => {
      receivedEvents.push({ user, amount, blockNumber: event.log.blockNumber });
    });

    await stakeToken.connect(alice).approve(await pool.getAddress(), stakeAmount);
    await pool.connect(alice).stake(stakeAmount);

    // Wait for event processing
    await new Promise(resolve => setTimeout(resolve, 100));

    pool.off(filter);

    expect(receivedEvents).to.have.length(1);
    expect(receivedEvents[0].user).to.equal(alice.address);
    expect(receivedEvents[0].amount).to.equal(stakeAmount);
  });

  it("queries historical events with getLogs", async function () {
    const { pool, stakeToken, alice, stakeAmount } = await loadFixture(deployAllContracts);

    await stakeToken.connect(alice).approve(await pool.getAddress(), stakeAmount);
    await pool.connect(alice).stake(stakeAmount);

    const filter = pool.filters.Staked();
    const events = await pool.queryFilter(filter, 0, "latest");

    expect(events.length).to.be.greaterThan(0);
    expect(events[0].args.user).to.equal(alice.address);
  });
});

Testing Error Handling in Your Application

Your application code should handle contract reverts gracefully. Test this:

// services/StakingService.js
class StakingService {
  constructor(pool, stakeToken, signer) {
    this.pool = pool.connect(signer);
    this.stakeToken = stakeToken.connect(signer);
    this.signer = signer;
  }

  async stake(amount) {
    try {
      const poolAddress = await this.pool.getAddress();
      const approveTx = await this.stakeToken.approve(poolAddress, amount);
      await approveTx.wait();

      const stakeTx = await this.pool.stake(amount);
      const receipt = await stakeTx.wait();

      return {
        success: true,
        txHash: receipt.hash,
        blockNumber: receipt.blockNumber,
      };
    } catch (error) {
      // Parse Ethers.js v6 custom errors
      if (error.data) {
        const decoded = this.pool.interface.parseError(error.data);
        return { success: false, error: decoded?.name, args: decoded?.args };
      }
      return { success: false, error: error.message };
    }
  }
}
// test/integration/StakingService.test.js
describe("StakingService", function () {
  it("returns success with tx hash on valid stake", async function () {
    const { pool, stakeToken, alice, stakeAmount } = await loadFixture(deployAllContracts);
    const service = new StakingService(pool, stakeToken, alice);

    const result = await service.stake(stakeAmount);

    expect(result.success).to.be.true;
    expect(result.txHash).to.match(/^0x[0-9a-f]{64}$/);
  });

  it("returns structured error when staking without balance", async function () {
    const { pool, stakeToken } = await loadFixture(deployAllContracts);
    const [,,,,, noBalance] = await ethers.getSigners();

    const service = new StakingService(pool, stakeToken, noBalance);
    const result = await service.stake(ethers.parseEther("100"));

    expect(result.success).to.be.false;
    expect(result.error).to.be.a("string");
  });
});

Comparing Ethers.js v6 vs Web3.js v4

Feature Ethers.js v6 Web3.js v4
Number type bigint native bigint native
Provider model JsonRpcProvider Web3 with plugins
Contract ABI ContractFactory + Contract new web3.eth.Contract(abi)
Gas estimation contract.method.estimateGas() contract.methods.fn().estimateGas()
Event queries contract.queryFilter(filter) contract.getPastEvents(name, options)
Bundle size Smaller (tree-shakeable) Larger
TypeScript First-class Improving

For new projects, Ethers.js v6 is generally preferred. For projects with existing Web3.js integrations, the migration cost is usually not worth it unless you're running into specific limitations.

Running Integration Tests in CI

# .github/workflows/integration.yml
name: Integration Tests
on: [push, pull_request]
jobs:
  integration:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - run: npm ci
      - name: Run integration tests (in-process Hardhat)
        run: npx hardhat test test/integration/**/*.test.js

For tests that need a persistent node:

      - name: Start Hardhat node
        run: npx hardhat node &
      - name: Wait for node
        run: npx wait-on http://127.0.0.1:8545
      - name: Deploy contracts
        run: npx hardhat run scripts/deploy.js --network localhost
      - name: Run integration tests
        run: npx hardhat test --network localhost

Summary

Integration testing with Ethers.js and Web3.js is how you verify that your JavaScript application correctly interacts with your smart contracts. The key practices:

  • Deploy fresh contracts in each test suite using fixtures
  • Test the full transaction lifecycle: send, wait, parse receipt
  • Test event emissions and subscriptions
  • Test your error handling code against real contract reverts
  • Use Hardhat Network's block mining controls for time-dependent logic

Unit tests tell you the Solidity is correct. Integration tests tell you the application is correct. You need both.

Read more

Start now free