reactjs - Jest 的问题和异步函数的调度
问题描述
我正在使用 React + Redux(带有 thunk)并且我正在使用 Jest 进行测试。我有下一个代码:
export const startUploading = (file) => {
return async(dispatch, getState) => {
const {active:activeNote} = getState().notes;
Swal.fire({
title: 'Uploading....',
text: 'Please wait...',
allowOutsideClick: false,
showConfirmButton: false,
willOpen: () => {
Swal.showLoading()
}
});
const fileUrl = await fileUpload(file);
activeNote.url = fileUrl;
//for pass tests!?
await dispatch(startSaveNote(activeNote));**
Swal.close();
}
};
和
export const startSaveNote = (note) => {
return async(dispatch, getState) => {
try {
const {uid} = getState().auth;
if(!note.url) delete note.url;
const noteToFirestore = {...note};
delete noteToFirestore.id;
await db.doc(`${uid}/journal/notes/${note.id}`)
.update(noteToFirestore);
dispatch(refreshNote(note.id, note));
Swal.fire('Saved', note.title, 'success');
}
catch(e) {
console.log(e);
}
}
};
测试是
test('should update the url of the entry - startUploading', async() => {
//const file = new File([], 'pic_testing.jpg');
await store.dispatch(startUploading(null));
const docRef = await db.doc(`/TESTING_UID/journal/notes/lirFobR2rpJijw0OcpOV`).get();
expect(docRef.data().url).toBe('https://test.com.vs.ps');
})
测试通过了,但我不得不在await dispatch(startSaveNote(activeNote));行中使用 await (这意味着我已经修改了我的源代码以使测试有效)。如果没有 await 运算符(在上一行),测试不会通过,因为await db.doc( ${uid}/journal/notes/${note.id}
).update(noteToFirestore); 不管用。
我的问题是:将 await 与调度功能一起使用的正确方法是什么?每次我调度的动作是异步的,我应该这样做吗?或者永远不应该使用运算符,这是一个笑话?
提前谢谢了!
解决方案
推荐阅读
- java - 带有随机对象的 while 循环的大 O 时间复杂度
- loopbackjs - 从 Loopback 4 模型导出数据库模式
- sql - 使用事务和显式锁对并发机制进行了哪些操作?
- python - Python 请求 - 无法登录网站
- python - python 3.x 中的多线程和子进程问题
- dymola - 如何在 dymola 中启用自动曼哈顿化模式?
- javascript - 是否有一种将标头添加到 $.ajax 帖子调用的全局方法?
- java - 为什么数组不采用前一条指令的值,而只采用最后一条指令的值?
- excel - 如何运行 VBA 宏来复制单元格中具有特定值的行并粘贴到另一个工作表?你能帮我修复这段代码吗?
- kubernetes - Prometheus 将所有节点名更改为小写