0

I have created a Ethereum dapp that has multiple contracts that access one another and use methods within each other. I would like to create a Javascript test which would emulate a use-case for this dapp. That is, my tests will have multiple msg.sender addresses and I want to make calls to multiple contracts. My dapp requires that certain state changes be made in one contract before another contract can be run. Here is a MWE of the test code I would like to run:

const Contract1 = artifacts.require("./C1.sol");
const Contract2 = artifacts.require("./C2.sol");

// First contract
// Do these tests first to modify the state of C1
contract("Contract1", async () => {
    await it("First test", () => {
        Contract1.deployed().then(instance => {
            return some_value_after_operations;
        }).then(function (result) {
            assert.equal(result, true);
        })
    });
})

// Second contract
// Do these tests after the first tests
contract("Contract2", async () => {
    await it("First test", () => {
        Contract2.deployed().then(instance => {
            return some_value_after_operations;
        }).then(function (result) {
            assert.equal(result, true);
        })
    });
})

The first tests should test the first contract, the second set of tests then need to test the second contract given that the first contract contains the state changes made during the first tests. I have tried multiple ways of trying to do this but each results in a "before each" hook: error. I have also tried reinstalling truffle and using other truffle versions.

How can I write a use-case test as described?

1 Answer 1

1

a possible way to write your testcase is like this:

const Contract1 = artifacts.require("./C1.sol");
const Contract2 = artifacts.require("./C2.sol");


contract("Test", accounts => {
    let result;

    // First contract
    // Do these tests first to modify the state of C1
    it("First test", async () => {
        const contract1 = await Contract1.deployed();
        result = await contract1.doSomething({from: accounts[0]);
        assert.equal(result, true);
    });

    // Second contract
    // Do these tests after the first tests and with the result of the first test
    it("Second test", async () => {
        const contract2 = await Contract2.deployed();
        const combinedResult  = await contract2.doSomething(result, {from: accounts[1]);
        assert.equal(combinedResult, true);
    });
})
1
  • Cool thanks, this actually is helpful for some of my tests! Commented Oct 27, 2021 at 20:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.