Ich teste den ERC20-Standard. Ich versuche, eine Transaktion von einem Konto mit balance=0 zu senden, was einen Fehler auslösen sollte. Ich versuche es zu fangen.
In meiner Testfunktion verwende ich Folgendes:
contract('erc20 deployed', function(accounts) {
it("should not transfer 1 token from address[0] to address[1]", function(done) {
try{
return erc20Instance.transfer(accounts[1], 1);
should.fail("No error was thrown trying to cheat balance");
}
catch(error){
done();
}
});
});
Wenn ich es mit Trüffeltest ausführe, erhalte ich die folgende Fehlermeldung:
1) Contract: erc20 deployed
should not transfer 1 token from address[0] to address[1]:
Uncaught Error: VM Exception while processing transaction: revert
Wie kann ich es fangen? Mein Ziel ist es, die Übertragungsfunktion zu testen und zu testen, dass Adresse [0] die Transaktion nicht effektiv durchführen kann.
Versuche dies:
contract('erc20 deployed', function(accounts) {
const REVERT = "VM Exception while processing transaction: revert";
it("should not transfer 1 token from address[0] to address[1]", async function() {
try {
await erc20Instance.transfer(accounts[1], 1);
throw null;
}
catch (error) {
assert(error, "Expected an error but did not get one");
assert(error.message.startsWith(REVERT), "Expected '" + REVERT + "' but got '" + error.message + "' instead");
}
});
});
Als Alternative zur Antwort von goodvibration ist es auch möglich, meine truffle-assertions
Bibliothek zu verwenden, die eine Hilfsfunktion enthält, um zu bestätigen, dass eine Vertragsfunktion zurückgesetzt wird.
Es kann über npm installiert werden
npm install truffle-assertions
Als nächstes kann es oben in Ihre Testdatei importiert werden
const truffleAssert = require('truffle-assertions');
Dann kann es in Ihrem Test verwendet werden:
contract('erc20 deployed', function(accounts) {
it("should not transfer 1 token from address[0] to address[1]", async function() {
await truffleAssert.reverts(erc20Instance.transfer(accounts[1], 1), null, "No error was thrown trying to cheat balance");
});
});
Die vollständige Dokumentation finden Sie auf GitHub .