测试坚固性时遇到麻烦

trouble when testing solidity

const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());
const { interface, bytecode } = require('../compile');

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', () => {
    assert.ok(inbox.options.address);
  });

  it('has a default message', async () => {
    const message = await inbox.methods.message().call();
    assert.equal(message, 'Hi there!');
  });

  it('can change the message', async () => {
    await inbox.methods.setMessage('bye').send({ from: accounts[0] });
    const message = await inbox.methods.message().call();
    assert.equal(message, 'bye');
  });
});

在 运行 上面的代码之后,我不断收到以下错误

inbox@1.0.0 测试C:\Users\user\Documents\inbox

mocha

收件箱 1) "before each" 挂钩 "deploys a contract"

0 次通过(98 毫秒) 1 失败

1) "before each" 挂钩 "deploys a contract": SyntaxError: JSON 中位置 0 的意外标记 u 在 JSON.parse () 在 Context.beforeEach (test\inbox.test.js:16:44) 在

npm 错误!代码生命周期 错误!错误号 1 错误! inbox@1.0.0 测试:mocha 错误!退出状态 1 错误! 错误!在 inbox@1.0.0 测试脚本中失败。 错误!这可能不是 npm 的问题。上面可能有额外的日志输出。

npm 错误!此 运行 的完整日志可在以下位置找到: 错误! C:\Users\user\AppData\Roaming\npm-cache_logs18-07-03T13_17_54_895Z-debug.log

C:\Users\user\Documents\inbox\测试>

当我在 compile.js 文件中将编码从 'UTF-8' 更改为 'utf8' 时,它起作用了。

我的 compile.js 文件如下所示

const path = require('path'); //for crossplatform
const fs = require('fs'); //file system
const solc = require('solc');

const inboxPath = path.resolve(__dirname, 'contracts', 'Inbox.sol');
const source = fs.readFileSync(inboxPath, 'utf8'); //change to utf8 to UTF-8

module.exports = solc.compile(source, 1).contracts[':Inbox'];

大家好,我也遇到过这个问题。 complie.js 文件中无需更改任何内容。 只是我们需要在声明部分

就像你的情况一样:

而不是写这个 const {interface, bytecode} = require("../compile")

我们可以这样写

const {interface} = require("../compile")
const {bytecode} = require("../compile")

在这种情况下,我们得到从 compile.js 文件导出的接口和字节码值。

卸载当前版本的 solidity 编译器并安装 solidity@0.4.17 (npm install --save solc@0.4.17) 并确保在源代码中提到了正确的版本 (pragma solidity ^0.4. 17).