Ethereum smart contracts – Testing with Truffle

Lucas Carballo
2018-10-16T19:56:24-03:00By |
April 16, 2018

Testing with Truffle

We already learnt how to set up a development environment, we saw an ICO example too. So, continuing with the Ethereum series, this post will focus on testing with truffle. In order to test a smart contract, we have some options with their own features to consider:

  1. If you test in the Ethereum main network: time depends on the network, it is public and have a real money cost.
  2. If you test in the Ethereum testnet networks: transaction completion time depends on the network, it is public and is free.
  3. Ethereum network simulator: fast, private and free.

This post will illustrate the option 3, because in development phase probably we will need to perform many tests.

Requirements

If you followed the last post, you just need to install Ganache CLI

npm install -g ganache-cli

If not (you should check our content here ? ), install truffle too

npm install -g truffle ganache-cli

You can download the truffle project from here

After downloading Ganache CLI, start your Ethereum network simulator executing the following command in a terminal.

ganache-cli

Keep in mind that without the last step, the proposed test in this post won’t work. If you want to work with an Ethereum testnet or with the mainnet you must configure your truffle project for that.

Begin to test

We can find in HelloWorld contract a function called sayHello(), that function returns a string “Hello world”

Use truffle to create a test file.

truffle create test HelloWorld

That will add a file called hello_world.js to test folder with a default test that checks if the contract is deployable. Let’s edit that test file for something more functional, the new test will allow us to check if our sayHello() function works properly.

var HelloWorld = artifacts.require('./HelloWorld.sol');

contract('HelloWorld:sayHello', function(accounts) {
  it("should return a correct string", function(done) {
    var hello_world = HelloWorld.deployed();
    hello_world.then(function(contract) {
      return contract.sayHello.call();
    }).then(function(result) {
      assert.isTrue(result === 'Hello world');
      done();
    })
  });
});

Note that HelloWorld.deployed() is a Promise, that is really useful since Ethereum networks calls are asynchronous.

Now, we are ready to run the test file.

truffle test ./test/hello_world.js

If you get a check mark, the first smart contract testing is done.

Simple as that!