如何在Chai测试中打印Solidity函数返回的双数组?
解决Chai测试中获取Solidity双数组返回值的问题
你的问题出在JavaScript的赋值语法上——Solidity函数返回的多个值在Ethers.js/Web3.js中会被封装成一个数组,而JS并不支持arr1,arr2 = await ...这种Python风格的多变量赋值,需要用数组解构来正确获取这两个数组。
修正后的代码示例
首先确保你的测试代码在async函数中执行(Chai/Mocha的测试用例可以直接声明为async),然后用数组解构获取返回值:
it("should fetch and print the buy order book", async function() { // 用数组解构直接获取两个返回数组 const [arrPricesBuy, arrVolumesBuy] = await exchangeInstance.getBuyOrderBook(tokenSymbol); // 打印结果,建议给变量起更有意义的名字方便调试 console.log("Buy order book prices:", arrPricesBuy); console.log("Buy order book volumes:", arrVolumesBuy); // 可选:添加Chai断言验证结果格式 expect(arrPricesBuy).to.be.an('array'); expect(arrVolumesBuy).to.be.an('array'); });
如果你用的是旧版Web3.js(非Ethers.js)
如果你的环境是旧版Web3,可能需要通过Promise的then方法处理返回值,写法如下:
exchangeInstance.getBuyOrderBook(tokenSymbol) .then(function(result) { // result是一个包含两个数组的数组,索引0是价格数组,索引1是数量数组 const arrPricesBuy = result[0]; const arrVolumesBuy = result[1]; console.log("Buy order book prices:", arrPricesBuy); console.log("Buy order book volumes:", arrVolumesBuy); }) .catch(function(error) { console.error("Failed to fetch order book:", error); });
关键注意点
- await只能在async函数中使用:如果你的测试代码不在async函数里,要么把测试用例声明为async,要么改用Promise的then/catch写法。
- 变量命名可读性:建议给数组起更贴合业务的名字(比如
arrPricesBuy而非arr1),方便调试和维护。 - Solidity函数的view修饰符:你的Solidity函数用了
constant,在Solidity 0.5.0+版本中已经被view替代,虽然不影响调用,但建议升级语法以保持兼容性。
内容的提问来源于stack exchange,提问作者heyooo12
相关产品推荐
相关产品推荐

