Solidity

從 JS 單元測試訪問契約變數

  • October 3, 2018

我在對合約進行單元測試時遇到問題:我正在使用 Mocha、Chai 和呼叫truffle test

我在測試LoanRecord.sol

contract LoanRecord {
 public bool on;
 ...

 constructor(...){
   ...
   on = false;
  }

 function external turnOn(){
   on = true;
 }
}

並在 record.test.js 中進行測試:

var assert = require('chai').assert
var LoanRecord = artifacts.require("../../contracts/record/LoanRecord.sol");

contract ('Record', function (accounts) {
   describe("#turnOn()", function () {
       it("should turn on a loan record instance", async function () {
           loanrecord = await LoanRecord.new(
               1,
               18,
               0x0000000000000000000000000000000000000002,
               0x0000000000000000000000000000000000000001, 
               "LOAN"
               );
           await assert.equal(loanrecord.on, false)
           await loanrecord.turnOn()
           await assert.equal(loanrecord.on, true)
       });
   });

但是,我收到:

1) Contract: Record
      #turnOn()
        should turn on a loan record instance:
    AssertionError: expected [Function] to equal false
     at Context.<anonymous> (test/record.js:15:26)
     at <anonymous>
     at process._tickCallback (internal/process/next_tick.js:188:7)

為什麼loanrecord.on返回[Function]而不是布爾類型?

已修復(也有 gitter@dwardu 幫助):

contract ('Record', function (accounts) {
   describe("#turnOn()", function () {
       it("should turn on a loan record instance", async function () {
           loanrecord = await LoanRecord.new(
               1,
               18,
               0x0000000000000000000000000000000000000002,
               0x0000000000000000000000000000000000000001, 
               "LOAN"
               );
           var on = await loanrecord.on()
           await assert.equal(on, false)
           await loanrecord.turnOn()
           var on = await loanrecord.on()
           await assert.equal(on, true)
       });
   });
}

您收到的錯誤消息為您提供了有關將函式與布爾值進行比較的良好提示。這意味著比較的一側是函式,一側是變數(或值)。

對於 Solidity 合約中的每個變數,都會自動生成一個公共 getter 函式。這意味著會自動生成一個帶有簽名的函式function on()來訪問變數的值on。因此,在訪問變數時,您還必須通過 getter 函式訪問它們。

改變你await assert.equal(loanrecord.on, true)await assert.equal(loanrecord.on(), true),它應該工作。或者您可能需要在比較await之前on()返回函式的值。

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