You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Hardhat测试智能合约时遇checkUpkeep未定义类型错误

解决Hardhat测试中Cannot read properties of undefined (reading 'checkUpkeep')错误

出现这个错误的核心原因是测试代码中的raffle变量未被正确赋值为合约实例,导致调用checkUpkeep方法时触发undefined属性读取错误。以下是具体排查和解决步骤:

1. 确保raffle合约实例已正确初始化

在测试的前置钩子(beforeEach或before)中完成合约部署,并将实例赋值给raffle变量。示例代码:

let raffle;
let interval;

beforeEach(async () => {
    // 获取合约工厂
    const Raffle = await ethers.getContractFactory("Raffle");
    // 初始化interval(根据你的合约构造函数参数调整)
    interval = ethers.BigNumber.from(30);
    // 部署合约,传入构造函数所需参数
    raffle = await Raffle.deploy(
        /* 替换为你的合约构造函数参数,比如VRF Coordinator地址、keyHash、interval等 */
    );
    await raffle.deployed();
});

2. 检查合约与方法名拼写

  • 确认测试中获取合约工厂的名称(Raffle)与Solidity合约的文件名、合约名完全一致(Solidity大小写敏感)。
  • 确保checkUpkeep方法名拼写无错误,包括大小写。

3. 验证网络环境配置

检查hardhat.config.js中的网络配置,确保测试使用的网络已正确部署合约,避免在未部署合约的网络上执行测试。

修正后的完整测试代码示例:

describe("checkUpkeep", () => {
    let raffle;
    let interval;

    beforeEach(async () => {
        const Raffle = await ethers.getContractFactory("Raffle");
        interval = ethers.BigNumber.from(30);
        raffle = await Raffle.deploy(/* 构造函数参数 */);
        await raffle.deployed();
    });

    it("returns false if people haven't sent any eth", async () => {
        await network.provider.send("evm_increaseTime", [interval.toNumber() + 1]);
        await network.provider.send("evm_mine", []);
        const { upkeepNeeded } = await raffle.callStatic.checkUpkeep("0x");
        assert(!upkeepNeeded);
    });
});

内容的提问来源于stack exchange,提问作者ameymeow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:45:15