1

I am trying to write mock a test for the following function call

const contract = await new web3.eth.Contract();

tx.data = await contract.methods
  .setup(
    [juryAddress, buyerAddress, sellerAddress],
    threshold,
    to,
    txData,
    fallbackHandler,
    paymentToken,
    0,
    sellerAddress
  )
  .encodeABI();

I am trying to mock this as a function contract.methods.setup() that returns a function object encodeABI() which then returns a dummy value {}.

The mock I am trying looks like this, although it is not working

const encodeABI = jest.fn()
encodeABI.mockReturnValue({})

const contract = {
    methods: {
        setup: jest.fn(),
    }
}

eth.Contract.mockResolvedValue(contract)
contract.methods.setup.mockResolvedValue(encodeABI)
expect(encodeABI).toBeCalled()

expect(encodeABI).toBeCalled() is not being called as I expect

4
  • mockResolvedValue() returns a Promise. Are you sure you don't just want contract.methods.setup.mockReturnValue(encodeABI) instead? Commented Jun 1, 2021 at 23:25
  • @Phil I thought I would want to return a promise for setup(), since contract.methods.setup() is async, right? Commented Jun 1, 2021 at 23:40
  • It doesn't appear to be. Your code just calls contract.methods.setup(...).encodeABI(). If anything, it's encodeABI() that should return a Promise since that's what you are awaiting Commented Jun 1, 2021 at 23:45
  • thanks, you are right, I think I have it backwards then. contract.methods.setup() returns a value, and .encodeABI() returns the Promise. Commented Jun 1, 2021 at 23:48

1 Answer 1

1

Your production code awaits encodeABI(), not setup(). It expects setup() to return an object with an encodeABI() function, not a Promise.

I would recommend making the following changes

const encodeABI = jest.fn(async () => ({})) // return a Promise here

const contract = {
    methods: {
        setup: jest.fn(() => ({ encodeABI })) // return an object with encodeABI
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.