Я начал модульное тестирование своих контрактов с 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
Надеюсь, поможет.
Исмаэль
Ник Каррауэй
Ник Каррауэй