assert statement in testing #5804
-
Hi, community! While doing the additional task at the end of lesson 6 (test addPerson function for 100% test coverage) a question popped up: Could we do more than one assert in it()? Tested code: // SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
contract SimpleStorage {
struct People {
uint256 favoriteNumber;
string name;
}
People[] public people;
mapping(string => uint256) public nameToFavoriteNumber;
function addPerson(string memory _name, uint256 _favoriteNumber) public {
people.push(People(_favoriteNumber, _name));
nameToFavoriteNumber[_name] = _favoriteNumber;
}
} Test code example with TWO asserts: const { ethers } = require("hardhat")
const { expect, assert } = require("chai")
describe("SimpleStorage", function () {
let simpleStorageFactory, simpleStorage
beforeEach(async function () {
simpleStorageFactory = await ethers.getContractFactory("SimpleStorage")
simpleStorage = await simpleStorageFactory.deploy()
})
it("Should save People struct in people array with favorite number and name. Also save the favorite number in nameToFavoriteNumber mapping", async function () {
const name = "Patrick"
const favoriteNumber = 7
const transactionResponse = await simpleStorage.addPerson(
name,
favoriteNumber
)
await transactionResponse.wait(1)
let arrEntry = await simpleStorage.people(0)
const mappingEntry = await simpleStorage.nameToFavoriteNumber(name)
assert.equal(mappingEntry.toString(), favoriteNumber.toString())
assert.equal(arrEntry.toString(), [favoriteNumber.toString(), name])
})
}) I feel that formatting should be better, but I am not sure about the right way how to fix it... By the way, this test is working. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Currently, im at lesson 9 and here is the thing that Patrick said: "Usually, we want to make sure that we have one assert per it but we'll have bunch here". So i guess best practice is using one assert&expect per it but he also used bunch of asserts at lesson 9. Since there is no problem with console we can use multiple asserts in my opinion. |
Beta Was this translation helpful? Give feedback.
Currently, im at lesson 9 and here is the thing that Patrick said: "Usually, we want to make sure that we have one assert per it but we'll have bunch here". So i guess best practice is using one assert&expect per it but he also used bunch of asserts at lesson 9. Since there is no problem with console we can use multiple asserts in my opinion.