Javascript Promise使用Mocha库引发错误

时间:2019-01-08 22:05:31

标签: javascript promise mocha web3

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()应该在执行测试用例之前完成。

屏幕截图-

2 个答案:

答案 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;
        })
});