我已经开始对我的合同进行测试(使用Javascript)。我对特弗莱和摩卡都很陌生,虽然我一直在努力学习教程,但我很难准确地了解每一步发生的事情。例如,下面的测试代码主要是工作的,但是我在测试第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);
}
}出于可读性的考虑,有些代码被故意省略,但这些函数是本测试中唯一相关的函数。
很抱歉,如果这暴露了缺乏理解的本质,但谁能向我解释为什么会发生这些失败呢?谢谢。
发布于 2018-03-11 01:52:25
从格式上看,这有点困难,但看起来变量meta可能超出了作用域,因此显示为未定义的变量。将meta的声明向上移动一个级别。
var meta;
it("should add the correct account to the whitelist", function(){
...或者,实例变量meta = instance;可能为null。你能用console.log(instance);检查一下吗?
发布于 2019-03-05 01:37:19
您的.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
复制相似问题