const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const inbox = require('../compile');
const web3 = new Web3(ganache.provider());
const interface = inbox.interface;
const bytecode = inbox.bytecode;
let contractAddress,inboxContract;
beforeEach(()=>{
// Get a list of all accounts
return web3.eth.getAccounts()
.then(accountList=>{
contractAddress = Array.from(accountList)[0];
return contractAddress;
})
.then(contractAddress=>{
inboxContract = new web3.eth.Contract(JSON.parse(interface))
.deploy({data: bytecode, arguments:['Hi there!']})
.send({from: contractAddress, gas: '1000000'});
return inboxContract;
})
//Use one of the accounts to deploy the contract
});
describe('Inbox contract test',()=>{
it('Successfully Deploy Test',()=>{
assert.ok(inboxContract.options.address);
})
it('Default Value test',()=>{
})
it('setMessage Test',()=>{
})
})
输出- 我希望beforeEach在运行it()块之前完全执行。我是否在Promise中缺少某些内容。 理想情况下,beforeEach()应该在执行测试用例之前完成。
屏幕截图-
答案 0 :(得分:0)
beforeEach
的代码应该放在describe
的内部,然后您可以使用async - await
代替标准的承诺,从而使语法更好。
这看起来像是
describe('Inbox contract test',()=>{
const inboxContract = new web3.eth.Contract(JSON.parse(interface))
beforeEach(async ()=>{
// Get a list of all accounts
const accountList = await web3.eth.getAccounts()
const contractAddress = Array.from(accountList)[0];
let receipt = await inboxContract.deploy({data: bytecode, arguments:['Hi there!']})
.send({from: contractAddress, gas: '1000000'});
//Use one of the accounts to deploy the contract
inboxContract.options.address = receipt.contractAddress
});
...
但是您必须确保测试运行inline
,因为全局inboxContract
变量将在每次测试之前被替换
答案 1 :(得分:0)
通过以下操作更改您的beforeEach
块
beforeEach(() => {
return web3.eth.getAccounts()
.then(accountList => {
return Array.from(accountList)[0];
})
.then(account => {
contractAddress = account;
return new web3.eth.Contract(JSON.parse(interface))
.deploy({ data: bytecode, arguments: ['Hi there!'] })
.send({ from: account, gas: '1000000' });
})
.then(contract => {
inboxContract = contract;
})
});