Parfois dans nos contracts nous voulons tester une interdiction de faire quelque chose
Par exemple l’interdiction d’envoyer moins d’ether que la somme minimale requise, ou alors nous voulons tester l’obligation d’envoyer des ether pour appeler une méthode
Notre fichier de test
it("requires a minimum amount of ether to enter", async () => {
try {
await lottery.methods.enter().send({
from: accounts[1],
value: 0,
});
assert(false);
} catch (err) {
assert(err);
}
});
it("only manager can call pickWinner", async () => {
try {
await lottery.methods.pickWinner().send({
from: accounts[1],
});
assert(false);
} catch (err) {
assert(err);
}
});
Pour ce faire nous utilisons un TRY CATCH !
On va essayer d’optimiser ce fonctionnement avec un fichier utils.js qui sera glissé dans un dossier /helpers dans notre dossier de /test
// utils/helper.js
const assert = require("assert");
async function shouldThrow(promise) {
try {
await promise;
assert(true);
}
catch (err) {
return;
}
assert(false, "The contract did not throw.");
}
module.exports = {
shouldThrow,
};
Nos test vont maintenant ressembler à
const { shouldThrow } = require('./utils/helper')
it("requires a minimum amount of ether to enter", async () => {
await shouldThrow(lottery.methods.enter().send({
from: accounts[1],
value: 0,
}))
});
it("only manager can call pickWinner", async () => {
await shouldThrow(lottery.methods.pickWinner().send({from: accounts[1]}))
});