Solidity

Truffle 智能合約測試不會重置狀態

  • November 11, 2021

javascript對一個簡單的 ERC 20 令牌進行了以下測試。呼叫中的哪個return token.balanceOf.call(accounts[2]);將獲取一些舊數據並從先前的測試事務中失敗,該事務編寫類似,但在同一合約的另一個 contract() 範圍內。使用 TestRpc

contract('ERC Allowance', function (accounts) {

   it("should be able to lend money and that user spend it", function () {
       var token;

       return Token.deployed().then(function (instance) {
           token= instance;
           return instance.approve(accounts[1], 5555, {from: accounts[0]});
       })
           .then(function (approveTransaction) {
               return chftoken .allowance.call(accounts[0], accounts[1]);
           })
           .then(function (allowance) {
               assert.equal(allowance, 5555, "allowance should be increased");
               return token.transferFrom.call(accounts[0], accounts[2], 55555, {from: accounts[1]});
           })
           .then(function (failedTransaction) {
               return token.balanceOf.call(accounts[2]);
           })
           .then(function (balance) {
               assert.equal(balance.valueOf(), 0, "transfer should not go through");
               return token.transferFrom.call(accounts[0], accounts[9], 10000, {from: accounts[1]});
           })
           .then(function (transactionCompleted) {
               return token.balanceOf.call(accounts[2])
           })
           .then(function (balance) {
               assert.equal(balance, 5555, "the balance should be transferred")
           });
   });
});

要重置狀態,您必須告訴測試套件在開始之前部署合約的新實例。

您可以使用 beforeEach() 告訴它在每個“它”之前部署一個新合約。每個測試都將從一個初始化狀態(和一個新的合約.deployed()地址)開始。

contract( ...

 var contract;

 beforeEach(function() {
    return Contract.new()
    .then(function(instance) {
       contract = instance;
    });
 });

 it("should ...

希望我沒有弄錯語法。松露 3.x 風格。

按照@rob 的回答,您還可以使用async看起來很乾淨的版本:

let contract;

beforeEach('should setup the contract instance', async () => {
 contract = await Contract.new();
});

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