English Article · Software

Unit-tests for blockchain smart contracts with Truffle

Sweet Tools for Smart Contracts | Truffle Suite

This post is to show how similar every technology to each other. If you experienced with NUnit, XUnit, Jasmine, Protractor, etc., you can easily figure out how to write unit-tests for blockchain smart-contracts using the Truffle tool which under the hood is NodeJS.

What do we have? A simple smart contract written on Solidity which creates an entity, for us it’s the Task.

pragma solidity >=0.4.22 <0.8.0;

contract TodoList {
    uint256 public taskCount = 0;

    struct Task {
        uint256 id;
        string content;
        bool completed;
    }

    mapping(uint256 => Task) public tasks;

    constructor() public {
        createTask("Check my portfolio ivanbrygar.net");
    }

    function createTask(string memory _content) public {
        taskCount++;

        tasks[taskCount] = Task(taskCount, _content, false);
    }
}

To test the smart contract we should create a JavaScript file under the test folder, for example test/TodoList.test.js:

const TodoList = artifacts.require("./TodoList.sol");

contract("TodoList", (accounts) => {
  before(async () => {
    this.todoList = await TodoList.deployed();
  });

  it("deployed successfully", async () => {
    const address = await this.todoList.address;
    assert.notEqual(address, 0x0);
    assert.notEqual(address, "");
    assert.notEqual(address, null);
    assert.notEqual(address, undefined);
  });

  it("lists tasks", async () => {
    const taskCount = await this.todoList.taskCount();
    const task = await this.todoList.tasks(taskCount);

    assert.equal(task.id.toNumber(), taskCount.toNumber());
    assert.equal(task.content, "Check my portfolio ivanbrygar.net");
    assert.equal(task.completed, false);
    assert.equal(taskCount.toNumber(), 1);
  });
});

As you can see, the structure has the familiar structure with tear down.

For run the tests, navigate to the root directory of the project in terminal/cmd and execute: truffle test command:

For the full project reference please refer to the GitHub repository: https://github.com/smitbmx/TodoList-Blockchain-Ethereum

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.