带有笑话的模拟函数,其中包含一个回调作为参数,该函数返回一个promise [英] Mock function with jest that contains a callback as an argument which returns a promise
问题描述
我正在与第三方脚本集成,并且遇到了一个我不知道如何正确测试的场景.
I'm integrating with a 3rd party script and have come across a scenario which I don't know how to test properly.
第三方脚本通过一些方法将对象添加到窗口. create方法的第二个参数是一个回调函数,该函数返回被拒绝或解决的Promise.
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.
我需要能够以拒绝状态或已解决状态来模拟第二个参数,以便我的单元测试可以涵盖是否用错误或成功消息来更新UI.
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)
})
})
以下是我当前尝试模拟不起作用的功能(针对window对象)的尝试.它没有正确设置拒绝值或解析值:(
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)))
任何帮助将不胜感激
推荐答案
create
是基于回调的,并且不了解promise,因此模拟也不应该包含promise.
create
is callback-based and is unaware of promises, so a mock shouldn't involve promises either.
鉴于thirdpartyform.create
是先前使用jest.mock
,jest.spyOn
等设置的间谍,是成功响应的模拟:
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'))
响应失败的模拟:
thirdpartyform.create.mockImplementation((options, cb) => cb({ reason: 'error' }))
这篇关于带有笑话的模拟函数,其中包含一个回调作为参数,该函数返回一个promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!