Solidity
測試合約時,NodeJS 返回:“SyntaxError: Unexpected token u in JSON at position 0”
我的 NodeJS 腳本給了我這個錯誤:
1)"before each" hook for "deploy a factory and a lottery" SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse((anonymous)) at Context.(anonymous) (test/lottery/test.js:18:46) at processTicksAndRejections(internal/process/task_queues.js:94:5)
文件 test.js
const assert = require('assert'); const ganache = require('ganache-cli'); const Web3 = require('web3'); const web3 = new Web3(ganache.provider()); const compiledFactory = require('../ethereum/build/LotteriaFactory.json'); const compiledLotteria = require('../ethereum/build/Lotteria.json'); //two istances of the contract inside the build dir let accounts; let factory; let lotteriaAddress; let lotteria; beforeEach(async () => { accounts = await web3.eth.getAccounts(); factory = await new web3.eth.Contract(JSON.parse(compiledFactory.interface)) .deploy({ data: compiledFactory.bytecode }) .send({ from: accounts[0], gas: '1000000' }); await factory.methods.createNew('5').send({ from: accounts[0], //manager gas: '1000000' }); const addresses = await factory.methods.active().call(); lotteriaAddress = addresses[0]; //[LotteriaFactory] lotteria = new web3.eth.Contract( JSON.parse(compiledLotteria.interface), lotteriaAddress ); }); describe('Lottery', () => { it('deploy a factory and a lottery', () => { assert.ok(factory.options.address); assert.ok(lotteria.options.address); }); });
我的依賴是:
- 溶膠 0.5.0
- 網路3 1.2.6
有人能幫我嗎?我錯過了什麼?
您的問題是嘗試
JSON.parse(compiledFactory.interface)
.函式
JSON.parse
需要一個表示有效 JSON 對象的輸入字元串。您正在嘗試通過需要JSON 文件來獲取該對象:
const compiledFactory = require('../ethereum/build/LotteriaFactory.json');
但是
require
語句被指定用於導入 JS 程式碼,而不是 JSON 對象!不需要這個文件,你應該簡單地閱讀它:
const fs = require('fs'); const compiledFactory = fs.readFileSync('../ethereum/build/LotteriaFactory.json', {encoding: "utf8"});
最後,為了訪問該
interface
對象的欄位,請更改:JSON.parse(compiledFactory.interface)
對此:
JSON.parse(compiledFactory).interface