使用Truffle测试Solidity合约时遇SyntaxError错误求助
解决Truffle测试中
SyntaxError: Unexpected token {的问题 你的错误根源很明确:在Truffle的CommonJS测试环境里使用了ES模块的import语法,而且你代码里的那行import完全是多余的,根本没用到。另外还有个小问题是断言方法用错了,我一起帮你修正。
具体解决步骤:
移除无用的
import语句
你的测试代码第一行import { isMainThread } from "worker_threads";既没有被使用,又违反了Truffle测试默认的CommonJS模块规则,直接删掉就行。修正断言方法的错误
你代码里写的AssertionError.equal是错误的用法,AssertionError是assert模块抛出错误的类,实际用来做断言的是assert.equal,需要先引入assert模块,或者用Truffle默认集成的Chai断言工具。
修正后的测试代码
下面是两种可行的写法,推荐第二种用async/await的风格,更简洁易读:
写法一:基于Promise链 + assert模块
var Election = artifacts.require("./Election.sol"); const assert = require("assert"); contract("Election", function(accounts){ it("initializes with two candidates", function(){ return Election.deployed().then(function(instance){ return instance.candidatesCount(); }).then(function(count){ assert.equal(count, 2); }); }); });
写法二:async/await风格(推荐)
var Election = artifacts.require("./Election.sol"); contract("Election", function(accounts){ it("initializes with two candidates", async function(){ const electionInstance = await Election.deployed(); const candidateCount = await electionInstance.candidatesCount(); assert.equal(candidateCount, 2); }); });
为什么会出现这个语法错误?
Truffle v5.x的测试框架基于Mocha,而Node.js 12的默认模块系统是CommonJS(用require引入模块),import是ES模块的语法,除非你专门配置Node支持ES模块(比如改文件后缀为.mjs或在package.json加"type": "module"),但Truffle的测试环境并不兼容这种配置,所以直接移除多余的import是最直接的解决方式。
内容的提问来源于stack exchange,提问作者Shreyas Jain
相关产品推荐
相关产品推荐

