Testing our token contract

As a first step, we need to create a new test file, and tell Truffle which contract we will be interacting with during the test. We can't use the contracts directly, because our JavaScript test framework has no way of understanding the Solidity code. Instead, we use a contract abstraction, which is created at compile time, and which can be included in our test file using Truffle's artifacts.require() syntax.

Create a new file in the test/ directory called PacktToken.test.js and add the following:

var PacktToken = artifacts.require('./PacktToken');

If you are familiar with Mocha, then you may expect our test file to include a call to describe(). Truffle, however, uses contract(), which behaves in the same way, but includes initialization and clean-up handling. Note that we pass a callback as the second parameter, and to that callback we're passing a reference to accounts. This makes Ganache's accounts available for the tests:

contract('PacktToken', async (accounts) => {

});

In our tests, we will use the JavaScript ES2017 async/await notation, but it's possible to use JavaScript ES2015 promises just as easily. Let's define a simple test first, then break down what it involves:

 it ('initialises the contract with the correct values', async () => {
let instance = await PacktToken.deployed();

let name = await instance.name();
assert.equal(name, 'Packt ERC20 Token', 'has the correct name');
});

This will be the basic form of our test cases. The preceding code does the following:

  • It defines a test case using Mocha's it() syntax.
  • It asynchronously gets a reference to our token contract, which has been deployed as part of the running truffle test.
  • Using the returned contract instance, it asynchronously calls into the contract to get the name of our token.
  • It asserts that the returned name is what we are expecting.

We could extend this initial test to include a further call to check the symbol in our contract:

   let symbol = await instance.symbol();
assert.equal(symbol, 'PET', 'has the correct symbol');

Our second test will check that, as part of the deployment, we passed the correct value for our token supply to the contract constructor:

 it ('allocates the total supply on deployment', async () => {
let instance = await PacktToken.deployed();

let supply = await instance.totalSupply();
assert.equal(supply, 1000000, 'sets the correct total supply');
});

We could write more tests specifically for the token contract, but instead we will implicitly test the code as part of testing the token sale contract.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset