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
相关产品推荐
相关产品推荐

