Web3js

ReferenceError:地址未定義

  • June 5, 2020
Truffle v5.0.5 (core: 5.0.5)
Solidity v0.5.0 (solc-js)
Node v10.15.1

ReferenceError:地址未定義。

const ApprovalContracts = artifacts.require('../../contracts/ApprovalContracts.sol'); // Pulls in my smart contract // the accounts are the 10 dummie ones
// the require pulls in the smart contract // the artifacts pulls in our code

contract ('ApprovalContracts', function (accounts) { // These are the accounts stored locally in the server the address
   //tests in javascript part of the contract //setup a contract and getting back the approver //takes a deposit im going to look and see what the balance is
   it('initiates contract', async function() { 
       const contract = await ApprovalContracts.deployed();
       const approver = await contract.approver.call(); 
       assert.equal(approver, 0xc7780C9521C2C2abED69f0D65BEbF9794C55ae94, "approvers don't match");
   });

   it('takes a deposit', async function() {
       const balance = await web3.eth.getBalance(address.contract);  -----> ReferenceError: address is not defined
       const expected = web3.utils.toBN(1e+18);
       assert.equal(balance.toString(), expected.toString(), "amount did not match");
   });
});

任何建議我將不勝感激。

const balance = await web3.eth.getBalance(address.contract);

你有兩個問題:

  • web3.eth.getBalance()返回一個 promiEvent 對象,以獲取您需要等待它的預期值
  • Javascript 不支持大數字,因此值被包裝在 BN 對像中,並且 assert 不知道如何將這些對象與數字進行比較

一種解決方案是將 BN 對象轉換為字元串以進行比較。

const balance = await web3.eth.getBalance(contract.address);
const expected = web3.utils.toBN(1e+18);
assert.equal(balance.toString(), expected.toString(), "amount did not match");

FWIW,我遇到了完全相同的問題,並讓我的測試像這樣通過:

// Truffle v5.1.23 (core: 5.1.23)
// Solidity - ^0.4.18 (solc-js)
// Node v12.14.1
// Web3.js v1.2.1


contract('ApprovalContract', function(accounts) {

 ...

 it('takes a deposit', async function () {
   const contract = await ApprovalContract.deployed();
   const balance = 1e+18;
   const expected = web3.utils.toBN(1e+18);
   await contract.deposit(accounts[1], {
     value: balance, from: accounts[0]
   });
   assert.equal(balance.toString(), expected.toString(), "amount did not match");
 });

});

我是一個完全的區塊鏈菜鳥,並且剛剛開始增加它,所以我不能說我的測試代表了一個真實的區塊鏈案例。但事情過去了。

此外,此程式碼來自 lynda.com 的乙太坊課程:它很好,但在發表此評論時它也快兩年了,從那時起只更新過一次。因此,正如該教程所說的那樣npm install -g truffle,我假設該教程使用的 truffle 版本比我們在完成操作時下載的版本舊,這導致了足夠的衝突,導致測試最初失敗。

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