【问题标题】:Test an onlyOwner function in Javascript在 Javascript 中测试 onlyOwner 函数
【发布时间】:2022-07-09 05:46:29
【问题描述】:

我的智能合约中有这种情况:

address[] public allowedUsers;

function allowUser(address _newUser) public onlyOwner {
   allowedUser.push(_newUser);
}

我正在使用 truffle 和他的测试套件,然后我写了这个案例,失败可能是因为我没有以正确的方式使用唯一的所有者方法:

const MyContract = artifacts.require("../contracts/MyContract.sol");

contract("MyContract", accounts => {
    it("should deploy the contract and allow the user", async () => {
        const contract = await MyContract.deployed();

        const account = accounts[0];
        const owner = await contract.owner.call()

        await contract.allowUser(account).call({ from: owner });

        const allowedUser = contract.allowedUser.call(0);

        assert.equal(whitelistedUser, account, 'new user is not allowed');
    })
});

有人可以帮我吗?

【问题讨论】:

    标签: javascript unit-testing solidity truffle


    【解决方案1】:

    假设你在合约中正确设置了所有者,在合约中为所有者写一个getter:

    function getContractOwner() public view returns (address)
      {
        return owner;
      }
    

    在 test.js 中

    contract("MyContract", accounts => {
         let _contract = null
         let currentOwner=null
    
        before(async () => {
          _contract = await MyContract.deployed();
          currentOwner = await _contract.getContractOwner()          
        })    
        it("should deploy the contract and allow the user", async () => {
            const account = accounts[0];
            await contract.allowUser(account, {from: currentOwner});
            // I assume this is retrieving data from a mapping
            const allowedUser = _contract.allowedUser.call(0);
            assert.equal(whitelistedUser, account, 'new user is not allowed');
        })
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-17
      • 2022-01-20
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多