BSC测试智能合约系统开发方案(程序代码)

2022-10-25 15:43:46 浏览数 (1)

测试合约

4.1 虚拟节点

ganache-cli

4.2测试用的模块

mocha

4.3 编写测试用例
代码语言:javascript复制
const path = require('path');
const assert = require('assert');

describe('测试课程的智能', () => {

    it('测试1 2是否等于3', () => {

        assert.equal(1   2, 3);
    })
})
4.4 测试合约方法
代码语言:javascript复制
const path = require('path');
const assert = require('assert');
const Web3 = require('web3')
const ganache = require('ganache-cli')
//const BigNumber = require('bignumber.js')
const web3 = new Web3(ganache.provider())
// 引入合约的json
const CourseList = require(path.resolve(__dirname, '../src/compiled/CourseList.json'))
const Course = require(path.resolve(__dirname, '../src/compiled/Course.json'))


// 定义几个全局变量,所有测试都需要
let accounts
// 实例
let courseList
let course

describe('测试课程的智能', () => {

    before(async () => {
        // 测试前的数据初始化
        accounts = await web3.eth.getAccounts()
        
        console.log(accounts)
        // 1. 虚拟部署一个合约
        courseList = await new web3.eth.Contract(JSON.parse(CourseList.interface))
            .deploy({ data: CourseList.bytecode })
            .send({
                // 最后一个是创建者
                from: accounts[9],
                gas: '5000000'
            })

    })

    it('合约部署成功', () => {
        assert.ok(courseList.options.address)
    })

    it('测试添加课程', async () => {
        const oldaddress = await courseList.methods.getCourse().call()
        assert.equal(oldaddress.length, 0)
        await courseList.methods.createCourse(
            '蜗牛的React课程'
        )
            .send({
                from: accounts[0],
                gas: '5000000'
            })
        const address = await courseList.methods.getCourse().call()
        assert.equal(address.length, 1)
				console.log(address)
    })

})
4.5 配置package.json
代码语言:javascript复制
"test:w": "mocha --watch"
4.6 运行指令

npm run test:w

0 人点赞