About the author
Every Truffle script is a Javascript app.
So, if you're familiar with writing Javascript, you already know how to write a Truffle script.
How do you write Truffle scripts to test your Solidity contracts? Before explaining, here's a simple test script:
"use strict"; const TestContract = artifacts.require('./testContract.sol'); contract('TestContract', function(accounts) { let wallet = accounts[2]; let anotherwallet = accounts[3]; let thirdwallet = accounts[4]; let TestContractInstance = null; beforeEach('setup contract for each test', async() => { TestContractInstance = await TestContract.new("Hello", 5); }) afterEach("name of test", async() => { }) it('should have value initialized', async() => { let value = await TestContractInstance.value(); assert.equal(value, 5); }) })
"use script" enables the strict mode for Javascript, which prevents variables from being used if they're not declared before. Each contract has a beforeEach and afterEach function, and both are optional. They allow you to do set up conditions, and clean up, before and after each test. A test is described by the anonymous function declared in the "it" function.
The contract function is passed an accounts array, and this is the 10 accounts which Truffle created when you run "truffle test" after a "truffle migrate".
Instead of using .then as described here on the Truffle site, I used async/await as it's easier to read. Essentially, the above test deploys the contract for every "it" function to be tested, so each time, it's a new contract. The "it" tests that the contract reads a value of 5. This format can be used to write and test any Solidity contract.
A method pointer is now the same as a global procedure, ie, procedure of object = procedure.