Solidity

為數組長度和內容編寫 Solidity 測試 (chai)

  • October 4, 2022

tdlr; 解決方案

我必須await使用我的斷言中使用的兩個值。為了獲取數組的長度,我需要在我的合約中添加一個新方法,如此處所示。原因在於接受的答案。

function getPeopleSize() public view returns (uint256) {
    return people.length;
}

這是傳遞it塊:

it("should add a person and their favorite number", async () => {
 const expectedValue = "11";
 const expectedName = "John";
 const transactionResponse = await simpleStorage.addPerson(
   expectedName,
   expectedValue
 );
 transactionResponse.wait(6);

 const johnValue = await simpleStorage.nameToFavoriteNumber(expectedName);
 const peopleSize = await simpleStorage.getPeopleSize();

 assert.equal(peopleSize, 1);
 assert.equal(johnValue, expectedValue);
});

我有一個函式addPerson,它儲存一個新名稱和最喜歡的號碼:

function addPerson(string memory _name, uint256 _favoriteNumber) public {
   people.push(People(_favoriteNumber, _name));
   nameToFavoriteNumber[_name] = _favoriteNumber;
}

people是一個數組並且favoriteNumber是一個 uint256。兩者都是公共數據類型。

uint256 favoriteNumber;

struct People {
 uint256 favoriteNumber;
 string name;
}

People[] public people;

mapping(string => uint256) public nameToFavoriteNumber;

例如,在我部署的 Remix 契約中,我可以nameToFavoriteNumber使用我添加的使用者字元串進行呼叫,並按預期返回提供的數字。但是,我不確定如何為該addPerson函式編寫測試,以確保確實儲存了姓名和收藏號碼。

這是我嘗試過的。的長度people列印為零,映射器列印undefined。我希望它以長度等於 1 且映射器等於 11 的方式通過。最後一點是我的其他測試正在通過,所以我確信simpleStorage合約在我的測試環境中正確部署。

it("should add a person and their favorite number", async () => {
   const expectedValue = "11";
   const expectedName = "John";
   const transactionResponse = await simpleStorage.addPerson(
     expectedName,
     expectedValue
   );
   transactionResponse.wait(6);

   const people = simpleStorage.people;

   const johnValue = simpleStorage.nameToFavoriteNumber[expectedName];

   assert.equal(people.length, 1);         // prints 0
   assert.equal(johnValue, expectedValue); // prints undefined
});

不知何故,我認為缺少關鍵字await以等待契約方法承諾得到解決,以及每個方法末尾的**()**。

檢查它是否有幫助。

it("should add a person and their favorite number", async () => {
   const expectedValue = "11";
   const expectedName = "John";
   const transactionResponse = await simpleStorage.addPerson(
     expectedName,
     expectedValue
   );

   // added await
   await transactionResponse.wait(6);

   // added await    
   // added () in the end (its a method)    
   // solidity retrieves only the value inside the position you pass. You must create a getPeopleSize method inside the contract to retrieve all length.
   const people = await simpleStorage.people(some index);

   // added await    
   // added () in the end (its a method)    
   const johnValue = await simpleStorage.nameToFavoriteNumber(expectedName);

   assert.equal(people.length, 1);
   assert.equal(johnValue, expectedValue);
});

引用自:https://ethereum.stackexchange.com/questions/136845