solidity智能合约[57]-测试web3j

安装模块

ganache-cli 代表本地测试网络
web3j 模块与以太坊进行交互

1
> npm install --save ganache-cli web3 mocha

使用mocha框架测试web3j,打印出账号

pachage.json:

1
2
3
"scripts": {
"test": "mocha"
},

helloworld.test.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const ganache = require('ganache-cli');

const Web3 = require('web3');
//构建web3j实例 , provider是连接web3j与以太坊的桥梁。这里由ganache-cli提供。
const web3 = new Web3(ganache.provider());

const assert = require('assert');

beforeEach( ()=>{
web3.eth.getAccounts().then(fetchAccounts=>{
console.log(fetchAccounts);
});
});
describe('HelloWorld',()=>{
it('deploy contract',()=>{})
})

测试

1
> npm test

打印出账号

下面的10个账号是本地测试网络ganache-cli自动生成的。

1
2
3
4
5
6
7
8
9
10
[ '0xa1ef752Cb11e41844898370b57d97A0E49Fe1B31',
'0x8D1b2f184408F3916c0d34045FFdBe175814F5d5',
'0x1c668849b383e87c4F6DCD6c0ee91D56187Cba13',
'0x68492B65b4bec8475E7112CC3Edd807cB23DAb6b',
'0xaF685ba6e028a592993A10c23C2E0875d95E974A',
'0x6226C34bf95aad9357120501f6D7651DDe925B6d',
'0xB31D3f8db004717d56BBc95e45d0762Dc473Ed18',
'0x28fFd75386de79f54cE1f9313F0F1C8f16B5Ec1e',
'0x2B34AD39b40D10A5D5D6d70eeAD2b9203C0858d0',
'0x478061329f8AfEF014a91e7A2aeAfE628D047eb2' ]

ES6新特性await与async

await与async处理异步操作,代码更加的优雅。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const ganache = require('ganache-cli');

const Web3 = require('web3');

const web3 = new Web3(ganache.provider());

const assert = require('assert');


beforeEach( async()=>{
fetchAccounts = await web3.eth.getAccounts();

console.log(fetchAccounts);
});

describe('HelloWorld',()=>{
it('fetchAccounts',()=>{})
})