My contract inherits the ownable.sol
which has a mint() method that is marked onlyOwner
like below:
function mint(address _to, string memory newTokenURI) public onlyOwner
I know that within the ownable
if the owner check fails it would return a rejected message "Ownable: caller is not the owner"
. I am trying to test my mint function's user access to do full test coverage. Note: I am using the chai-matchers library
describe("EFTContract", function () {
let token721;
let TEST_URI1 = "ipfs://tokenurifor1";
beforeEach(async function () {
EFT721Contract = await ethers.getContractFactory("EFTNFT");
[owner, account1, ...otheraccounts] = await ethers.getSigners();
token721 = await EFT721Contract .deploy();
});
describe("Ownership Tests", function () {
// ok
it("Testowner can call mint()", async function () {
expect(await token721.mint(account1.address, TEST_URI1)).to.not.be.reverted;
});
// fails
it("Test guest should not call mint()", async function () {
// mint 1 so we have a valid token to try to query with tokenURI()
await token721.mint(account1.address, TEST_URI1);
// connect to guest account to try and mint
await expect(token721
.connect(account1.address)
.mint(account1.address, TEST_URI1))
.to.be.rejectedWith("Ownable: caller is not the owner");
});'
});
When I run this the first test passes but the second fails with the following error:
"VoidSigner cannot sign transactions (operation=\"signTransaction\", code=UNSUPPORTED_OPERATION, version=abstract-signer/5.6.2)"
I know I can replace that assert to pass the test replacing it with the code below but I believe that isnt properly testing ownership access of the ownable.sol contract:
await expect(token721
.connect(account1.address)
.mint(account1.address, TEST_URI1))
.eventually.to.rejectedWith(Error, "VoidSigner cannot sign transactions (operation=\"signTransaction\", code=UNSUPPORTED_OPERATION, version=abstract-signer/5.6.2)");
How can I instead modify the second test case to properly compare against `"Ownable: caller is not the owner"?
Solution: It looks like I should wait for the promise to resolve before comparing the results. In this case it would provide an error instead of a rejected messaged so I should use .to.be.revertedWith()
instead.
// mint
it("Testowner can call mint()", async function () {
expect(await token721.mint(account1.address, TEST_URI1)).to.not.be.reverted;
});
it("Test guest should not call mint()", async function () {
await expect(token721
.connect(account1)
.mint(account1.address, TEST_URI1))
.to.be.revertedWith("Ownable: caller is not the owner");
});