2

Say I have contract Foo:

contract Foo {

event OwnerAdded(address indexed owner);

address public owner;

constructor(address _owner) {
    owner = _owner
    emit OwnerAdded(owner)
}

How would I write my hardhat test to check for the OwnerAdded() emit?

I was trying to do:

await expect(fooFactory.deploy(testAddr)).to.emit(Foo, "OwnerAdded).withArgs("0x83h342e46571f77h0531d")

But obviously, that doesn't work because you need the contract object to pass to the Chai emit assertion.

1
  • 1
    I know this is now what you're looking for but testing things like this is easy-peasy in Foundry Apr 8, 2023 at 20:05

2 Answers 2

0

You would need to send the deploy transaction and wait for the receipt, and then check if it emitted the desired event, something like this:

const tx = fooFactory.deploy(testAddr);
const receipt = await tx.wait();
const event = receipt.events
        ?.filter(({ event }) => event == "OwnerAdded")
expect(event).to.not.be.null;
expect(event.args.owner).to.be.equals("0x83h342e46571f77h0531d");
1
  • 2
    I tried this but I get the error: "tx.wait is not a function"
    – Rohan Nero
    Oct 30, 2022 at 17:14
0

This is the right way to do it as the previous answer fails with tx.wait is not a function:

const tx = fooFactory.deploy(testAddr);
const receipt = await tx.deployTransaction.wait();
const event = receipt.events.find(event => event.event === "OwnerAdded");
const [owner] = event.args;
expect(event).to.not.be.null;
expect(owner).to.equal("0x83h342e46571f77h0531d");

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.