在 Javascript 中测试 onlyOwner 函数
Test an onlyOwner function in Javascript
我的智能合约中出现这种情况:
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');
})
});
有人可以帮助我吗?谢谢大家!
假设你在合约中正确设置了owner,在合约中为owner写一个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');
})
});
我的智能合约中出现这种情况:
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');
})
});
有人可以帮助我吗?谢谢大家!
假设你在合约中正确设置了owner,在合约中为owner写一个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');
})
});