Mock function with jest that contains a callback as an argument which returns a promise

血红的双手。 提交于 2021-01-29 07:47:42

问题


I'm integrating with a 3rd party script and have come across a scenario which I don't know how to test properly.

The 3rd party script adds an object to the window with a few methods. The second argument of the create method is a callback function which returns a promise that is either rejected or resolved.

I need to be able to mock that second argument with either a reject or resolved status so that my unit test can cover whether the UI is updated with either the error or success message.

How can I mock this function and the callback function with the proper response?

thirdpartyform.create(options, (err, message) => {
  return new Promise((resolve, reject) => {
    if (err) {
      reject(err.reason)
    } else {
      resolve(message)
    }
  })
  .then(message => {
    setState(message)
  })
  .catch((err) => {
    setState(err)
  })
})

Below is my current attempt at mocking the function (against the window object) which is not working. It does not properly set the rejected value or resolved value :(

create: jest.fn((options, callback) => callback(jest.fn().mockRejectedValue(FORM_TIMEOUT)))

Any help would be greatly appreciated


回答1:


create is callback-based and is unaware of promises, so a mock shouldn't involve promises either.

Given that thirdpartyform.create is a spy that has been previously set up with jest.mock, jest.spyOn, etc, a mock for successful response:

thirdpartyform.create.mockImplementation((options, cb) => cb(null, 'message'))

A mock for unsuccessful response:

thirdpartyform.create.mockImplementation((options, cb) => cb({ reason: 'error' }))


来源:https://stackoverflow.com/questions/64099600/mock-function-with-jest-that-contains-a-callback-as-an-argument-which-returns-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!