javascript - 如何在 Jest 中模拟 Promise 解析函数
问题描述
我正在使用 Jest + Enzyme。我有一个功能,
submitHandler = values => {
return new Promise((resolve, _) => {
saveSomething({values, resolve});
}
}
我的测试:
it('Should call saveSomething on form submit', () => {
const values = {firstName: 'FName', lastname: 'LName'};
const {enzymeWrapper, props} = setup();
enzymeWrapper.find('Formik').simulate('submit', values);
expect(props.saveSomething).toBeCalledWith({
values: {
...values,
contactLanguage: LOCALE_TO_LANGUAGE_MAP[props.locale],
},
});
});
目前,我的测试失败了。错误:
Error: expect(jest.fn()).toBeCalledWith(...expected)
- Expected
+ Received
@@ -1,6 +1,7 @@
Object {
+ "resolve": [Function anonymous],
"values": Object {
"contactLanguage": "FRENCH",
"firstName": "FName",
"lastname": "LName",
},,
问题:如何模拟解析功能?
解决方案
Jest mocks have an inherent method to cope with Promise resolutions and rejections. Please refer to the Jest Mock API for details.
The mockResolvedValue
method is used for this very purpose.
Just mock your submitHandler with a simple call to jest.fn()
and add the mockResolvedValue
method.
You can test rejections as well with the mockRejectValue
method.
推荐阅读
- pytorch - DataParallel 如何确定我要使用哪个 gpu?
- c# - IdentityRole 和 IdentityUser 之间的网络核心区别
- neo4j - Cypher Query 需要很长时间才能找到结束节点
- python - 删除以 '.' 结尾的特定行的最后一个字符
- javascript - 使用javascript切换功能后,如何在浏览器调整大小时使导航链接重新出现/重置为默认值?
- c# - 如何防止其他程序重命名其他顶级窗口标题
- python - 计算一段时间内的平均值,而不是组内的平均值
- r - 使用 dplyr 进行分组数据帧扩展
- powerbi - 电源 BI。将“空白”值替换为 0,但它在数据库中不为空
- c# - 如何为 DataGridView 中的特定单元格定义恒定大小?