Solidity

請問為什麼我在安全帽中執行測試時會出現此錯誤?

  • July 29, 2022

每當我執行測試命令時,我都會收到此錯誤:

 0 passing (3s)
 1 failing

 1) Crud uint test
      Initial form must be empty:
    ReferenceError: createForm is not defined
     at Context.<anonymous> (test\uint\Crud.test.js:18:12)
     at Context.<anonymous> (test\uint\Crud.test.js:18:5)
     at processTicksAndRejections (node:internal/process/task_queues:96:5)
     at runNextTicks (node:internal/process/task_queues:65:3)
     at listOnTimeout (node:internal/timers:528:9)
     at processTimers (node:internal/timers:502:7)

————這就是我的程式碼的樣子—————

這是我的契約:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract Crud {
   uint256 private age;
   string public name = "";
   // address creator;

   // constructor(address) {
   //     creator = msg.sender;
   // }

   function createForm(
       uint256 _age,
       string memory _name
       // address
   ) public {
       age = _age;
       name = _name;
       // creator = msg.sender;
   }

   function deleteForm() public {
       delete age;
       delete name;
   }

   function getForm()
       public
       view
       returns (
           uint256,
           string memory /*,
           address*/
       )
   {
       return (age, name /*, creator*/);
   }
}

這是我的測試文件。

const { expect, assert } = require("chai");
const { network, deployments, ethers } = require("hardhat");

describe("Crud uint test", () => {
 let crud, deployer;
 const name = "";
 const age = 0;

 beforeEach(async () => {
   deployer = (await getNamedAccounts()).deployer;
   const Crud = await ethers.getContractFactory("Crud");
   crud = await Crud.deploy();
   await crud.deployed();
 });

 it("Initial form must be empty", async () => {
   await crud.createForm(age, name);
   assert(crud.createForm.name, name);
 });
});

兩個問題:

首先,您使用assert不正確。to 的第一個參數assert是斷言本身,並且必須評估為trueor false,其中第二個參數是可選的失敗消息。

其次,你在斷言crud.createForm.name哪個不存在;crud.createForm是一個函式。

根據您的契約,解決方案是將您的assert行替換為:

const form = await crud.getForm();
assert(form[0] === age, "age does not match");
assert(form[1] === name, "name does not match");

請注意,您不能使用form.name並且form.age因為返回值在您的契約中未命名。

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