Truffle

無法使用 Javascript 進行 Truffle 測試

  • January 2, 2022

我已經開始使用 Truffle 對我的合約進行單元測試(使用 Javascript)。我對 Truffle 和 Mocha 都很陌生,雖然我嘗試按照教程進行操作,但我很難準確地理解每一步發生的事情。例如,以下測試程式碼大部分都有效,但我在測試第 27 行收到錯誤:

whiteListLength = meta.getWhiteListLength.call();

帶有錯誤消息:“無法讀取未定義的屬性“呼叫””。完整的測試在這裡:

it("should add the correct account to the whitelist", function(){
 var account_one = accounts[0];
 var whiteListLength;
 var isAccountWhiteListed;
 var meta;

 return EMBallot.deployed().then(function(instance) { 
     meta = instance;
 return meta.addToWhiteList.call(account_one);
})

.then(function(){
whiteListLength = meta.getWhiteListLength.call();//this line is the problem
return meta.amIWhitelisted.call(account_one); 
})

.then(function(response) {
 isAccountWhiteListed = response;

 assert.equal(whiteListLength, 1, "Whitelist should have exactly one member");
 assert.isTrue(isAccountWhiteListed);
//here comes the assertions
});

對於帶有程式碼的契約:

pragma solidity ^0.4.19;

contract EMBallot {

address[] whiteList;
struct Proposal {
   uint voteCount;//how many votes this proposal has received
   string description;//what this option is about, what you are voting for
}
struct Voter {
   bool voted;//if true, has already voted and any further attempts to vote are automatically ignored
   uint8 vote;
   string name;
}
Proposal[] proposals;  

address admin; //there should only be one admin per election, this variable stores the address designated as the admin.    
mapping(address => Voter) voters;//this creates a key-value pair, where addresses are the keys, 
and Voter structs(objects) are the values. 

function EMBallot() public{
admin = msg.sender;
}

function getWhiteListLength() constant returns(uint256){
   return whiteList.length;
}

function amIWhitelisted(address myAddress) constant returns(bool){
for(uint i=0; i<=whiteList.length; i++){//iterate over whiteList
if(myAddress == whiteList[i]){//i checked, you CAN use == on addresses
return true;
break;
}
return false;
}}

function addToWhiteList (address voter){
whiteList.push(voter);   
}
}

出於可讀性目的,故意省略了一些程式碼,但這些函式是與本測試目的唯一相關的函式。

抱歉,如果這暴露了缺乏理解的基本要素,但誰能向我解釋為什麼會發生這些失敗?謝謝。

從格式中很難分辨,但看起來變數meta可能超出範圍,因此顯示為未定義。將聲明上移meta一個級別。

var meta;    
it("should add the correct account to the whitelist", function(){
...

或者,您的實例變數meta = instance;可能為空。你能檢查一下嗎console.log(instance);

你的.thens和斷言在你的it()塊之外。你想完成你的合約交易和呼叫序列,並使用斷言,全部在裡面 it

試試這個

var myContact;
var response1;
var response2;

it("should ...", function() {
 MyContract.deployed() // no return
 .then(function(instance) {
   myContract = instance;
   return myContract.doSomething()
 })
 .then(function(response) {
   response1 = response;
   return myContract.somethingElse()
 })
 .then(function(response) {
   response2 = response;
   assert.equal(response1.toString(10),2,"response1 should be 2");
   assert.strictEqual(response2,false,"response2 isn't false");
 });
}); // this closes the it() block

希望能幫助到你。

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