首页 > 解决方案 > 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 与调度功能一起使用的正确方法是什么?每次我调度的动作是异步的,我应该这样做吗?或者永远不应该使用运算符,这是一个笑话?

提前谢谢了!

标签: reactjsreduxjestjsthunk

解决方案


推荐阅读