简体   繁体   English

开玩笑,如何模拟由模拟的 function 返回的 function

[英]Jest, how to mock a function returned by a mocked function

I am trying to write mock a test for the following function call我正在尝试为以下 function 调用编写模拟测试

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 {} .我试图将其模拟为 function contract.methods.setup()返回一个 function object encodeABI()然后返回一个虚拟值编码{}

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

Your production code awaits encodeABI() , not setup() .您的生产代码等待encodeABI() ,而不是setup() It expects setup() to return an object with an encodeABI() function, not a Promise .它期望setup()返回 object 和encodeABI() function,而不是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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM