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

Solidity智能合约测试报错:TypeError: artifacts is not a function

解决Truffle测试中TypeError: artifacts is not a function错误

这个报错是测试文件里的一个语法小失误,很容易排查,我来给你拆解一下:

错误根源

你在Helloworldtest.js的第一行写了:

const Helloworld = artifacts().require("Helloworld");

在Truffle的测试环境中,artifacts是一个内置对象,require是它的方法——你多写了一对()把artifacts当成函数调用,这就直接导致了artifacts is not a function的错误。

修复方案

把测试文件的第一行代码改成正确的写法即可:

const Helloworld = artifacts.require("Helloworld");

额外优化建议(可选)

顺便帮你检查了其他代码,有两个小细节可以优化:

  • 测试断言:Solidity返回的字符串是经过包装的对象,直接用===严格相等可能会出现预期外的问题,建议改用Mocha提供的assert.equal方法,兼容性更好:
    assert.equal(message, "Hello Again!");
    
  • setMessage函数的payable修饰符:如果这个函数不需要接收ETH,建议去掉payable,避免后续开发中误转ETH到合约里无法取出。

修正后的完整测试文件代码:

const Helloworld = artifacts.require("Helloworld");
contract("Helloworld", async function(){
    it("should initialize correctly", async function(){
        let instance = await Helloworld.deployed();
        let message = await instance.getMessage();
        assert.equal(message, "Hello Again!");
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 12:12:37