我目前正在学习Solidity并尝试构建一个简单的合约。我还在尝试使用 Mocha 框架在部署之前测试智能合约。测试代码如下:
const assert = require("assert");
const ganache = require("ganache-cli");
const Web3 = require("web3");
const { interface, bytecode } = require("../compile");
const provider = ganache.provider();
const web3 = new Web3(provider);
let accounts;
let inbox;
beforeEach(async () => {
// Get a list of all accounts
accounts = await web3.eth.getAccounts();
// Use one of those accounts to deploy the contract
inbox = await new web3.eth.Contract(JSON.parse(interface))
.deploy({
data: bytecode,
arguments: ["Hi there!"]
})
.send({
from: accounts[0],
gas: "1000000"
});
});
describe("Inbox", () => {
it("deploys a contract", () => {
console.log(inbox);
});
});
测试失败并超时:
> mocha
Inbox
1) "before each" hook for "deploys a contract"
0 passing (2s)
1 failing
1) "before each" hook for "deploys a contract":
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
我注意到如果我注释掉 send(( 参数,测试就会通过:
// .send({
// from: accounts[0],
// gas: "1000000"
// });
所以问题一定是使用这种方法。不确定这是否是异步问题。
我通过将 web3 降级到 1.0.0-beta.37
来解决这个问题。似乎版本 1.0.0-beta.51
有问题。