簡體   English   中英

Jest mockRejectedValue 在節點中拋出未處理的承諾拒絕

[英]Jest mockRejectedValue throws unhandled promise rejection in node

我正在嘗試開玩笑地編寫一個測試,但是當我嘗試使用mockRejectedValue時不斷收到 UnhandledPromiseRejectionWarning

代碼如下所示:

it('Should set error message when call fails', async () => {
        const context = mockActionsContext();
        const user = {
            username: 'alice',
            password: 'password'
        };

        const getError = new Error('network error');

        (AuthService.login as jest.Mock) = jest.fn().mockRejectedValue(getError);
        await actions[ActionTypes.USER_LOGIN](context, user);

        // Check is the commits are called
        expect((context.commit as any).mock.calls).toEqual([
            [MutationTypes.USER_LOGIN],
            [MutationTypes.USER_LOGIN_ERROR, 'Oops, something went wrong. Try again later!']
        ]);

        // Login service is called with user login
        expect(AuthService.login as jest.Mock).toHaveBeenCalledWith(user);
    });

AuthService.login返回一個 axios.post,我嘗試用模擬覆蓋它。 actions[ActionTypes.USER_LOGIN](context, user)調用 Authservice.login

測試正在通過,但我不希望任何未處理的承諾拒絕。 有人知道如何解決嗎?


編輯@goodmorningasif 感謝您的回復。 我已經看它太久了 :)

操作如下所示:

    [ActionTypes.USER_LOGIN]: ({ commit }: Context, payload: User) => {
        return new Promise((resolve, reject) => {
            commit(MutationTypes.USER_LOGIN);

            AuthService.login(payload)
                .then((token) => {
                    commit(MutationTypes.USER_LOGIN_SUCCESS, token);

                    localStorage.setItem('user-token', token);
                    client.defaults.headers.common.Authorization = `Bearer ${token}`;
                    resolve(token);
                })
                .catch((error) => {
                    let errorMessage = 'Oops, something went wrong. Try again later!';

                    if (error?.response?.status === 401) {
                        errorMessage = 'Unknown username and password combination!';
                    }

                    localStorage.removeItem('user-token');

                    commit(MutationTypes.USER_LOGIN_ERROR, errorMessage);
                    reject(error);
                });
        });
    },

解決方案

在我的情況下,這個動作是返回一個承諾女巫會被拒絕。 在測試中,我直接調用操作而不是捕獲拒絕。

await actions[ActionTypes.USER_LOGIN](context, user).catch(() => null);

這修復了它。

我們可以看到動作和減速器代碼嗎? 您的錯誤中可能有錯誤:)

您正在測試登錄函數是否被調用並且操作返回您設置的錯誤消息,但您正在假設導致錯誤的原因。 也許這不是因為mockRejectedValue /'network error'。

我建議在操作有效負載中包含實際的錯誤消息以及您的錯誤消息:一個用於開發人員和調試,一個用於讓用戶知道下一步要做什么。

我還發現這有助於理解UnhandledPromiseRejectionWarninghttps : //thecodebarbarian.com/unhandled-promise-rejections-in-node.js.html

順便說一句,找出問題的好本能,而不是滿足於通過測試!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM