简体   繁体   English

测试 safeMint function

[英]Testing the safeMint function

I am trying to successfully write a unit test for my safeMint function below.我正在尝试为下面的 safeMint function 成功编写单元测试。

Here is my current test:这是我目前的测试:

const assert = require("assert");
const { accounts } = require("@openzeppelin/test-environment");
const ComNFT = artifacts.require("ComNFT");
const { expect } = require("chai");

// describe('ComNFT', () => {
// let accounts;
let comNFT;

beforeEach(async () => {
  accounts = await web3.eth.getAccounts();
  comNFT = await ComNFT.new({ from: accounts[0] });
  //comNFT = await ComNFT.at("");
  // console.log(comNFT.address);
});


  it('should fail when called by a non-owner account', async () => {
    try {
      await web3.eth.sendTransaction({
        from: accounts[1], // The non-owner account
        to: comNFT.address, // The contract address
        data: comNFT.methods.safeMint(accounts[1], 'token URI').encodeABI() // The function call and arguments, encoded as ABI
      });
      assert.fail('Expected error not thrown');
    } catch (error) {
      assert(error.message.includes('onlyOwner'), 'Expected "onlyOwner" error message not found');
    }
  });

  it('should be able to mint a new token', async () => {
    await web3.eth.sendTransaction({
      from: accounts[0], // The owner account
      to: comNFT.address, // The contract address
      data: comNFT.methods.safeMint(accounts[1], 'token URI').encodeABI() // The function call and arguments, encoded as ABI
    });

    const tokenURI = await comNFT.tokenURI(1); // Assume the token ID is 1
    assert.equal(tokenURI, 'token URI');
  });
    function safeMint(address to, string memory uri) public onlyOwner {
        uint256 tokenId = _tokenIdCounter.current();
        _tokenIdCounter.increment();
        _safeMint(to, tokenId);
        _setTokenURI(tokenId, uri);
    }

I am getting a failure message after i run npx truffle test " 1) "before each" hook for "should fail when called by a non-owner account"在我运行 npx truffle test“1)”之后,我收到一条失败消息“在每个”钩子之前“当被非所有者帐户调用时应该失败”

0 passing (3s) 1 failing 0 通过(3 秒) 1 失败

  1. "before each" hook for "should fail when called by a non-owner account": TypeError: Assignment to constant variable. “在每个之前”挂钩“当被非所有者帐户调用时应该失败”:TypeError:分配给常量变量。 at Context.在上下文中。 (test/ComNFT.js:11:12)" (测试/ComNFT.js:11:12)”

Can someone suggest a way of me successfully writing a test that calls safeMint?有人可以建议我成功编写调用 safeMint 的测试的方法吗?

The other test "itshould fail when called by a non-owner account" is also not running?另一个测试“当被非所有者帐户调用时它应该失败”也没有运行?

Thanks谢谢

safeMint function has onlyowner modifir, you should call safeMint function with the owner address that is accounts[0] (not accounts[1]) safeMint function 只有所有者修改,你应该调用 safeMint function,所有者地址是 accounts[0](不是 accounts[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM