Truffle
Truffle 測試中的單個異常會導致所有其他測試案例失敗
我正在為我的契約製作測試腳本,它看起來像
contract('...', async () => { let token = null; before('deploy', async () => { token = await MyContract.new(...); }); it('should success', async() => { ... }); it('should fail', async() => { ... }); // work as intended only until here it('should success', async() => { ... }); });
並用命令執行
truffle test ./test/test.js
問題是第二次之後的呼叫
it(...)
,即合約呼叫失敗並呼叫revert
,永遠不會成功並引發類似於AssertionError: the tx doesn't have the correct nonce. account has nonce of: 37 tx has nonce of: 36
如何使測試腳本工作?看起來某種隨機數增量出錯了,但我不確定我做錯了什麼。我正在使用 Ganache GUI 2.0.1 來測試網路和 truffle v5.0.9。
- 編輯 -
正如評論所建議的,我檢查我是否錯過了任何
await
關鍵字,我的程式碼都是這樣的,
it('should deny transfer with insufficient (zero) balance', async () => { const amount = web3.utils.toWei('1', 'ether'); const promise = token.transfer.call(accounts[3], amount, { 'from': accounts[2] }); await assert.isRejected(promise, 'revert', 'transfer transaction with insufficient (zero) balance must be denied'); });
我嘗試了然後 TL 建議的,
it('should deny transfer with insufficient (zero) balance', async () => { const amount = web3.utils.toWei('1', 'ether'); const promise = token.transfer(accounts[3], amount, { 'from': accounts[2] }); await truffleAssert.reverts(promise, 'revert', 'transfer transaction with insufficient (zero) balance must be denied'); });
但這並不能解決問題。現在的解決方法是呼叫預期會失敗的合約呼叫
.call
,例如const promise = token.nope.call(1, 2, 3, { 'from': accounts[0] });
但萬一真的出現意外錯誤,這是不可避免的,應該是一回事。使用多個
contract(...)
.
token.transfer(accounts[3], amount, { 'from': accounts[2], nonce: await web3.eth.getTransactionCount(accounts[2]) });
添加 nonce 參數將解決問題,它對我有用
使用松露斷言庫,正如 goodvibration 所說,不要忘記等待
const truffleAssert = require('truffle-assertions'); ... it('should fail', async function () { await truffleAssert.fails(<your_contract>.<your_function>(..., { from: ... })); });