Saltar al contenido principal

Unit Tests

How to build unit tests for your smart contract.


Getting Started

No smart contract is complete without having been thoroughly tested. To test your smart contract, write unit tests inside of the /tests/module-tests.js file. Continue refining your contract and redeploying until you're happy with your smart contract.

1

Additional resources

Haven't written your smart contracts? See Smart Contracts before moving forward. Check out the Chai assertion library, and Hardhat for additional resources to help you get started.

Update module-test.js

The module-test.js file should contain all of the unit tests for your smart contract. To complete this file, update the module description, module name, and add unit tests for each of your smart contract functions to match your smart contract.

// Update file name to match smart module (ex. ERC721-test.js)
const { ethers } = require("hardhat");
const { expect } = require("chai");

// Update module description
describe("Module", function () {
let Module;
let ModuleFactory;
let moduleContract;
let factoryContract;
let alice;

beforeEach(async () => {
// Update module name
Module = await ethers.getContractFactory("Module");
[owner, alice, bob, cara] = await ethers.getSigners();

// Update occurrences of module name
moduleContract = await Module.deploy(owner.address);
await moduleContract.deployed();

// Update occurrences of module factory
ModuleFactory = await ethers.getContractFactory("ModuleFactory");
factoryContract = await ModuleFactory.deploy(
// Update name of moduleContract
moduleContract.address,
owner.address
);
});

describe("Initial", function () {
it("Checking owner", async () => {
// Update name of moduleContract
expect(await moduleContract.contractOwner()).to.equal(owner.address);
});
});

// Add unit tests for all smart contract functions
});
Example

View an example of a completed module-test.js file at sample-test.js.

JavaScript API

You're now ready to start building your JavaScript API!

→
Step 4: JavaScript API
javascript-api