Unit Testing in Truffle

const People = artifacts.require(“People”);
const truffleAssert = require(“truffle-assertions”);

contract(“People”, async function(accounts){
let instance;

before(async function() {
    instance = await People.deployed();
})

it("shouldnt create a person with age over 150 years", async function(){
    await truffleAssert.fails(instance.createPerson("Edson", 200, 180, {value: web3.utils.toWei("1", "ether")}), truffleAssert.ErrorType.REVERT);  
});

it("shouldn't create without payment", async function() {
    await truffleAssert.fails(instance.createPerson("edson", 134, 180, {value: "1000"}), truffleAssert.ErrorType.REVERT); 
});

it("should set senior statues correctly", async function() {
    await instance.createPerson("edson", 65, 190, {value: web3.utils.toWei("1", "ether")});
    let result = await instance.getPerson();
    assert(result.senior === true, "senior level not set");
});

it("should set age correctly", async function() {
    let result = await instance.getPerson();
    assert(result.age.toNumber() === 65, "Age not set correctly");
});

it("should increase balance when person is created", async function() {
    const initialBalance = await web3.eth.getBalance(instance.address);
    await instance.createPerson("Edd", 37, 129, {value: web3.utils.toWei("1", "ether"), from: accounts[3]});

    assert((parseInt(initialBalance) + 1000000000000000000) === parseInt(await web3.eth.getBalance(instance.address)));
});

it("should set balance to 0 when all money is withdrawed", async function() {
    let result = await instance.withdrawAll();
    assert.equal(await web3.eth.getBalance(instance.address), 0);
});

})

1 Like

Hi @EdsonRamirez

Your tests are correct well done , but next time plz use the preformatted text tag to display your code :wink:

prefromatted_text-animated

const People = artifacts.require(“People”);
const truffleAssert = require(“truffle-assertions”);

contract ("People", async function(accounts){
    it("shouldn't create a person with age over 150 years", async function(){
      let instance = await People.deployed();
      await truffleAssert.fails(instance.createPerson("Bob", 200, 190, {value: web3.utils.toWei("1", "ether")}), truffleAssert.ErrorType.REVERT);
    });
    it("shouldn't create a person without payment", async function(){
      let instance = await People.deployed();
      await truffleAssert.fails(instance.createPerson("Bob", 50, 190, {value: 1000}), truffleAssert.ErrorType.REVERT);
    });
    it("should set senior status correctly", async function(){
      let instance = await People.deployed();
      await instance.createPerson("Bob", 65, 190, {value: web3.utils.toWei("1", "ether")});
      let result = await instance.getPerson();
      assert(result.senior === true, "Senior level not set");
    });
    it("should set age correctly", async function(){
      let instance = await People.deployed();
      let result = await instance.getPerson();
      assert(result.age.toNumber() === 65, "Age not set correctly");
    });

//added tests
it(“should only allow owner to delete person”, async function(){
let instance = await People.deployed();
await instance.createPerson(“Bob”, 15, 187, {value: web3.utils.toWei(“1”, “ether”)});
await truffleAssert.fails(instance.deletePerson(accounts[0], {from: accounts[1]}), truffleAssert.ErrorType.REVERT);
});
it(“should only be deleted by contract owner”, async function(){
let instance = await People.deployed();
await instance.deletePerson(accounts[0]);
let result = await instance.getPerson();
assert(result.age.toNumber() === 0, “Person was not deleted by contract owner”);
})
});

I had to get help on this one
//web3.eth.getBalance(address)
it(“should add 1 eth to balance after createPerson call”, async function(){
let instance = await People.new();
await instance.createPerson(“Steve”, 44, 187, {from: accounts[2], value: web3.utils.toWei(“1”, “ether”)});

      let balance = await instance.balance();
      let floatBalance = parseFloat(balance);

      let realBalance = await web3.eth.getBalance(instance.address);
      assert(floatBalance == web3.utils.toWei("1", "ether") && floatBalance == realBalance)
    })
    it("should allow owner to withdraw balance", async function(){
      let instance = await People.new();
      await instance.createPerson("Amber", 25, 160, {from: accounts[2], value: web3.utils.toWei("1", "ether")});
      await truffleAssert.passes(instance.withDrawAll({from: accounts[0]}));
    });
    it("should only allow owner to withdraw balance", async function(){
      let instance = await People.new();
      await instance.createPerson("Amber", 25, 160, {from: accounts[2], value: web3.utils.toWei("1", "ether")});
      await truffleAssert.fails(instance.withDrawAll({from: accounts[2]}), truffleAssert.ErrorType.REVERT);
    });
    it("should have increased owner's balance after withdrawl", async function(){
      let instance = await People.new();
      await instance.createPerson("Tom", 45, 160, {from: accounts[2], value: web3.utils.toWei("1", "ether")});

      let balanceBefore = parseFloat(await web3.eth.getBalance(accounts[0]));
      await instance.withDrawAll();
      let balanceAfter = parseFloat(await web3.eth.getBalance(accounts[0]));
      assert(balanceBefore < balanceAfter, "Owner's balance was not increased after withdrawl");
    });
    it("should have balance of 0 after withdrawl", async function(){
      let instance = await People.new();
      await instance.createPerson("Tom", 45, 160, {from: accounts[2], value: web3.utils.toWei("1", "ether")});

      await instance.withDrawAll();

      let balance = await instance.balance();
      let floatBalance = parseFloat(balance);

      let realBalance = await web3.eth.getBalance(instance.address);
      assert(floatBalance == web3.utils.toWei("0", "ether") && floatBalance == realBalance, "Contrat balance was not at 0 after withdrawl")
    })

});

Plz @mjwatson10 read the message about it s the same for you
prefromatted_text-animated

It’s impossible to read your test …

const People = artifacts.require("People");
const truffleAssert = require("truffle-assertions");

    contract ("People", async function(accounts){

      let instance;

      //used if new istance is needed for each test
      beforeEach(async function(){
        instance = await People.deployed();

      //used for instance that are resusinf info
      //  before(async function(){
      //    instance = await People.deployed();

      //these two work the same just after the test however
      //after()
      //afterEach()

      });

        it("shouldn't create a person with age over 150 years", async function(){
          //beforeEcach is run prior to each test
          let instance = await People.deployed();
          await truffleAssert.fails(instance.createPerson("Bob", 200, 190, {value: web3.utils.toWei("1", "ether")}), truffleAssert.ErrorType.REVERT);
        });
        it("shouldn't create a person without payment", async function(){
          let instance = await People.deployed();
          await truffleAssert.fails(instance.createPerson("Bob", 50, 190, {value: 1000}), truffleAssert.ErrorType.REVERT);
        });
        it("should set senior status correctly", async function(){
          let instance = await People.deployed();
          await instance.createPerson("Bob", 65, 190, {value: web3.utils.toWei("1", "ether")});
          let result = await instance.getPerson();
          assert(result.senior === true, "Senior level not set");
        });
        it("should set age correctly", async function(){
          let instance = await People.deployed();
          let result = await instance.getPerson();
          assert(result.age.toNumber() === 65, "Age not set correctly");
        });
        it("should only allow owner to delete person", async function(){
          let instance = await People.deployed();
          await instance.createPerson("Bob", 15, 187, {from: accounts[1], value: web3.utils.toWei("1", "ether")});
          await truffleAssert.fails(instance.deletePerson(accounts[1], {from: accounts[1]}), truffleAssert.ErrorType.REVERT);
        });
        it("should only be deleted by contract owner", async function(){
          let instance = await People.new();
          await instance.createPerson("Bob", 15, 187, {from: accounts[1], value: web3.utils.toWei("1", "ether")});
          await truffleAssert.passes(instance.deletePerson(accounts[1], {from: accounts[0]}));
        });
        //web3.eth.getBalance(address)
        it("should add 1 eth to balance after createPerson call", async function(){
          let instance = await People.new();
          await instance.createPerson("Steve", 44, 187, {from: accounts[2], value: web3.utils.toWei("1", "ether")});

          let balance = await instance.balance();
          let floatBalance = parseFloat(balance);

          let realBalance = await web3.eth.getBalance(instance.address);
          assert(floatBalance == web3.utils.toWei("1", "ether") && floatBalance == realBalance)
        })
        it("should allow owner to withdraw balance", async function(){
          let instance = await People.new();
          await instance.createPerson("Amber", 25, 160, {from: accounts[2], value: web3.utils.toWei("1", "ether")});
          await truffleAssert.passes(instance.withDrawAll({from: accounts[0]}));
        });
        it("should only allow owner to withdraw balance", async function(){
          let instance = await People.new();
          await instance.createPerson("Amber", 25, 160, {from: accounts[2], value: web3.utils.toWei("1", "ether")});
          await truffleAssert.fails(instance.withDrawAll({from: accounts[2]}), truffleAssert.ErrorType.REVERT);
        });
        it("should have increased owner's balance after withdrawl", async function(){
          let instance = await People.new();
          await instance.createPerson("Tom", 45, 160, {from: accounts[2], value: web3.utils.toWei("1", "ether")});

          let balanceBefore = parseFloat(await web3.eth.getBalance(accounts[0]));
          await instance.withDrawAll();
          let balanceAfter = parseFloat(await web3.eth.getBalance(accounts[0]));
          assert(balanceBefore < balanceAfter, "Owner's balance was not increased after withdrawl");
        });
        it("should have balance of 0 after withdrawl", async function(){
          let instance = await People.new();
          await instance.createPerson("Tom", 45, 160, {from: accounts[2], value: web3.utils.toWei("1", "ether")});

          await instance.withDrawAll();

          let balance = await instance.balance();
          let floatBalance = parseFloat(balance);

          let realBalance = await web3.eth.getBalance(instance.address);
          assert(floatBalance == web3.utils.toWei("0", "ether") && floatBalance == realBalance, "Contrat balance was not at 0 after withdrawl")
        })

});
1 Like

Good tests @mjwatson10 :+1:
Thank you for the reformatted code :pray:
Only one small thing , you don’t need to do

let instance = await People.deployed();

in all your test because you have

      beforeEach(async function(){
        instance = await People.deployed();
     }

At the top of your test so the instance used will be the one deployed, so you are doing it twice :wink:

1 Like
it("should let contract owner delete", async function(){
  let instance = await People.new();
  await instance.createPerson("Chillie", 26, 190, {from: accounts [2], value: web3.utils.toWei("1", "ether")});
  await truffleAssert.passes(instance.deletePerson(accounts[1],{from:accounts [0]}));

});
it("shouldn't let noneowner delete", async function(){
  let instance = await People.deployed();
  await instance.createPerson("Dawid", 43, 169, {from: accounts [3], value: web3.utils.toWei("1", "ether")});
  await truffleAssert.fails(instance.deletePerson(accounts[3], {from: accounts [3]}), truffleAssert.ErrorType.REVERT);

  });

**Shout out to @gabba for fixing my code in comments. **

1 Like
it("should pay into the account upon person creation", async function(){
  let internBal = instance.balance();
  let chainBal = await web3.eth.getBalance(People.address);
  await instance.createPerson("Rosie", 21, 166, {from: accounts[2], value: web3.utils.toWei("1","ether")});
  await  truffleAssert.passes(internBal === chainBal);
})

it("should allow owner to withdraw all from contract", async function(){
  let instance = await People.new();
  await instance.createPerson("Rosie", 21, 166, {from: accounts[1], value: web3.utils.toWei("1","ether")});
  await instance.withdrawAll({from: accounts[0]});
  await truffleAssert.passes(instance.withdrawAll({from: accounts[0]}));
})

1 Like
    it("shouldn't deletePerson(...) if the user is not the contract owner.",
        async function(){
            await instance.createPerson("Chadrick", 65, 190, {value: web3.utils.toWei("1", "ether"), from: accounts[1]});
            let result = await instance.getPerson({from: accounts[1]});
            assert(result.name === "Chadrick", "Person is not the correct person.");
            await truffleAssert.fails(
                instance.deletePerson(accounts[1], {from: accounts[1]}),
                truffleAssert.ErrorType.REVERT
            );
        }
    );

    it("should deletePerson(...) if the user is the contract owner.",
        async function(){
            await instance.createPerson("Chadrick2", 60, 190, {value: web3.utils.toWei("1", "ether"), from: accounts[2]});
            let result = await instance.getPerson({from: accounts[2]});
            assert(result.name === "Chadrick2", "Person is not the correct person.");
            await instance.deletePerson(accounts[2], {from: accounts[0]});
            let result2 = await instance.getPerson({from: accounts[2]});
            assert(result2.name === "", "Person was not deleted correctly.");
        }
    );
1 Like
it("should autorize only the owner to delete person", async () => {
        let instance = await People.deployed();
        await instance.createPerson('Bob', 55, 174, {from : accounts[1], value: web3.utils.toWei('1', 'ether')});
        await instance.deletePerson(accounts[1], {from : accounts[0]});
        let result = await instance.getPerson({from : accounts[1]});
        assert(result.name === "");
        assert(result.age.toNumber() == 0);
        assert(result.height.toNumber() == 0);
    });
    it("shouldn't autorize other user than owner to delete person", async () => {
        let instance = await People.deployed();
        await instance.createPerson('Bob', 55, 174, {from : accounts[1], value: web3.utils.toWei('1', 'ether')});
        await truffleAssert.fails(instance.deletePerson(accounts[1], {from : accounts[1]}), truffleAssert.ErrorType.REVERT);
    });
1 Like
it("should increase the balance of People contract by 1 ether", async () => {
        let balanceBefore = await web3.eth.getBalance(instance.address);
        await instance.createPerson('Bob', 55, 174, {from : accounts[0], value : web3.utils.toWei('1', 'ether')});
        let balanceAfter = await web3.utils.fromWei(await web3.eth.getBalance(instance.address), "ether");
        assert(balanceAfter - balanceBefore == 1, "should increase by one ether");
    });
    it("should authorize owner to get all ether of People contract withdraw and increase balance of owner by 1 ether", async () => {
        let balanceOfOwnerBeforeW = await web3.utils.fromWei(await web3.eth.getBalance(accounts[0]), "ether");
        await instance.createPerson('Bob', 55, 174, {from : accounts[1], value : web3.utils.toWei('1', 'ether'), gasPrice : 0});
        await instance.withdrawAll({from: accounts[0], gasPrice : 0});
        let balanceOfOwnerAfterW = await web3.utils.fromWei(await web3.eth.getBalance(accounts[0]), "ether");

        assert(balanceOfOwnerAfterW - balanceOfOwnerBeforeW == 1, "should increase by one ether");
    });
    it("shouldn't authorize other user to get all ether of People contract withdraw", async () => {
        await instance.createPerson('Bob', 55, 174, {from : accounts[1], value : web3.utils.toWei('1', 'ether')});
        await truffleAssert.fails(instance.withdrawAll({from: accounts[1]}), truffleAssert.ErrorType.REVERT);
    })
1 Like

Hi Filip . Please Help. I ve got this error during the first Migration:
(I have downgraded Nodejs to version 10.18)


2_People_migration.js

C:\Users\Tung NT\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:352968
throw new Error(“Could not find artifacts for " + import_path + " from any sources”);
^

Error: Could not find artifacts for People from any sources…

Can you paste your code for 2_People_migration.js?

Thank you. I solved the problem…
I restarted Ganache, added new project and fix some typo in People_migration file.

1 Like

Hey @filip!
I’ve been haveing truble geting the test to pass. I was wondering if you could help out. I thought that you should know that i’m not through the Multiple Tests video yet, I am only half way.
Here is the peopletest.js code in case there is anything wrong with it.

const People = artifacts.require("People");
const truffleAssert = require("truffle-assertions");

contract("People", async function(){
    it("Shouldn't create a person with age over 150 years", async function(){
        let instance = await People.deployed();
        await truffleAssert.fails(instance.createPerson("Bob", 200, 190, {value: web3.utils.toWei("1", "ether")}), truffleAssert.ErrorType.REVERT);
    });
      it("shouldn't create a person without payment", async function(){
        let instance = await People.deployed();
        await truffleAssert.fails(instance.createPerson("Bob", 50, 190, {value: 1000}), truffleAssert.ErrorType.REVERT);
  });
  it("should set senior status correctly", async function(){
        let instance = await People.deployed();
        await instance.createPerson("Bob", 65, 190, {value: web3.utils.toWei("1", "ether")});
        let result = await instance.getPerson();
        assert(result.senior === true, "Senior level not set");
  })
});


Here is the errer.

Please let me know if you need anymore code.

it("shouldn't delete person for non-owner", async function(){
    let instance = await People.deployed();
    await instance.createPerson("Dave", 80, 140, {value: web3.utils.toWei("1", "ether"), from accounts[1]});
    truffleAssert.fails(instance.deletePerson(accounts[1], {from: accounts[1]}));
});

it("should delete person for owner", async function(){
    await instance.deletePerson(accounts[0], {from: accounts[0]});
    let person = await instance.getPerson();
    assert(person.name === "");
});
1 Like
	it("should update balance for new person", async function(){
		let instance = await People.new();
		await instance.createPerson("Bob", 90, 140, {value: web3.utils.toWei("1", "ether"), from: accounts[1]});
		let blockchainBalance = await web3.eth.getBalance(instance.address);
		assert(parseInt(blockchainBalance) === parseInt(web3.utils.toWei("1", "ether")));		
	});

	it("should contract balance to 0 on withdrawAll", async function(){
		await instance.withdrawAll();
		let blockchainBalance = await web3.eth.getBalance(instance.address);
		assert(parseInt(blockchainBalance) === 0);		
	});

	it("should funds to owner balance on withdrawAll", async function(){
		await instance.createPerson("Bob", 90, 140, {value: web3.utils.toWei("1", "ether"), from: accounts[1]});
		let oldFunds = parseInt(await web3.eth.getBalance(accounts[0]));
		let contractFunds = parseInt(await web3.eth.getBalance(instance.address));
		await instance.withdrawAll();
		let newFunds = parseInt(await web3.eth.getBalance(accounts[0]));
		let gasMargin = parseInt(web3.utils.toWei("10", "milli"))
		console.log(parseInt(oldFunds), parseInt(contractFunds), parseInt(newFunds));
		assert(newFunds -gasMargin <= parseInt(oldFunds)+parseInt(contractFunds) <= parseInt(newFunds)+gasMargin);		
	});

Owner test


const People = artifacts.require("People");
const truffleAssert = require("truffle-assertions");

contract("People", async function(accounts){
   it("shouldn't delete person without beeing owner", async function(){
        let instance = await People.deployed();
        await instance.createPerson("Masha", 27, 110, {value: web3.utils.toWei("1","ether")}); // account[0]
        await truffleAssert.fails(instance.deletePerson(accounts[0], {from: accounts[1]}), truffleAssert.ErrorType.revert);
    });
    it("should delete persen correctly", async function(){
        let instance = await People.deployed();
        await instance.deletePerson(accounts[0]);
        assert(instance.getPerson().name === "", "Delete failed. Person exists: " + instance.getPerson().name);
    });
});

Edit by @gabba : can you use the Preformatted text tag to display your code @Stas_Simon ? thx you

1 Like
const People = artifacts.require("People");
const truffleAssert = require("truffle-assertions");

contract("People", async (accounts) => {
  let instance;
  let owner;
  beforeEach(async () => {
    instance = await People.deployed();
    owner = accounts[0];
  });

  it("should be able to delete person", async () => {
    await instance.createPerson("Bob", 21, 70, {
      value: web3.utils.toWei("1", "ether"),
    });
    let person = await instance.getPerson();
    assert(person.name === "Bob", "Person should be created with name Bob");
    instance.deletePerson(owner);
    person = await instance.getPerson();
    assert(person.name === "", "Person should be deleted");
  });

  it("should not be able to delete person", async () => {
    const nonOwner = "dummyAddress";
    await instance.createPerson("Bob", 21, 70, {
      value: web3.utils.toWei("1", "ether"),
    });
    let person = await instance.getPerson();
    assert(person.name === "Bob", "Person should be created with name Bob");
    await truffleAssert.fails(instance.deletePerson(nonOwner));
  });
});
1 Like