Truffle
松露測試未連接到 Ganache
我在我的開發環境中使用 Truffle 和 Ganache。使用 truffle 控制台或 truffle 外部腳本一切正常,但 truffle 測試似乎沒有連接到 Ganache:
當執行
truffle exec ./script.js --network ganache
一切按預期工作時。它顯示了正確的合約地址(在 Ganache UI 中可見),在 Ganache 中我可以看到合約已經執行的交易。Using network 'ganache'. Test contract fetched 0xee09Bb5C1B6703f03db3263de408200ee134324D BN { negative: 0, words: [ 0, <1 empty item> ], length: 1, red: null } BN { negative: 0, words: [ 11, <1 empty item> ], length: 1, red: null }
但是當執行
truffle test --network ganache
一個不同的合約地址時,我在 Ganache UI 中找不到,並且在 Ganache 中沒有交易可見。然而,這些交易似乎是在某個地方執行的,但顯然不是在 Ganache。Using network 'ganache'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Contract: 1st Test Test contract fetched 0xD8F3b0A6B0Db4325ea309C7ac8e5CE17AB22D322 BN { negative: 0, words: [ 0, <1 empty item> ], length: 1, red: null } BN { negative: 0, words: [ 11, <1 empty item> ], length: 1, red: null } ✓ should have set correct id (173ms)
知道為什麼
truffle test
不連接到 Ganache 嗎?在我的配置下面:
版本
Truffle v5.3.0 (core: 5.3.0) Solidity - 0.8.3 (solc-js) Node v15.13.0 Web3.js v1.2.9
松露-config.js
networks: { ganache: { host: "127.0.0.1", port: 7545, network_id: "*", } }
合約測試.sol
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract Test { uint public id = 0; function setId(uint _id) public { id = _id; } function getId() public view returns (uint) { return id; } }
腳本.js
module.exports = async function(callback) { const Test = artifacts.require("Test"); try { // Init const instance = await Test.deployed(); console.log('Test contract fetched', instance.address); // Get ID var id = await instance.getId(); console.log(id); // Set ID await instance.setId(11); // Get ID id = await instance.getId(); console.log(id); } catch (error) { console.error(error); } callback(); }
測試.js
const Test = artifacts.require("Test"); contract("1st Test", async accounts => { it ("should have set correct id", async ()=> { const instance = await Test.deployed(); console.log('Test contract fetched', instance.address); var id = await instance.getId(); console.log(id); await instance.setId(11); var id = await instance.getId(); console.log(id); assert.equal(id, 11); }); });
同時,感謝這篇博文,我發現了這個問題:https ://forum.openzeppelin.com/t/truffle-tests-not-being-run-against-contract-deployed-to-ganache-instead-uses-another-合約地址/4402/15
概括
- Truffle 測試總是部署一個新合約以確保測試在一個乾淨的合約上執行(但是我無法讓它在 Ganache UI 中可見)
- 在遷移腳本中添加
overwrite: false
作為部署函式的參數似乎可以解決問題- 但是,在我使用的版本中,僅添加覆蓋參數不起作用,僅在添加另一個參數時,例如“來自”
使用以下部署腳本可以連接
truffle test
到 Ganache UI 中可見的現有合約:module.exports = async function (deployer) { const accounts = await web3.eth.getAccounts(); await deployer.deploy(Test, {from: accounts[0], overwrite: false}); this.deployedTest = await Test.deployed(); console.log(`Migrations deployed Test Contract: ${this.deployedTest.address}`); };