开玩笑,如何模拟被模拟函数返回的函数

时间:2021-06-01 22:52:52

标签: javascript unit-testing jestjs web3

我正在尝试为以下函数调用编写模拟测试

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

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

我试图将它模拟为一个函数 contract.methods.setup(),它返回一个函数对象 encodeABI(),然后返回一个虚拟值 {}

我正在尝试的模拟看起来像这样,虽然它不起作用

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() 没有像我预期的那样被调用

1 个答案:

答案 0 :(得分:0)

您的生产代码等待 encodeABI(),而不是 setup()。它期望 setup() 返回一个带有 encodeABI() 函数的对象,而不是一个 Promise

我建议进行以下更改

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

const contract = {
    methods: {
        setup: jest.fn(() => ({ encodeABI })) // return an object with encodeABI
    }
}