2017-10-15 110 views
3

我寫了一個異步JavaScript函數,雖然似乎沒有得到我期望的返回值。有人可以解釋一下,如果我誤解了異步函數的工作原理,或者如果我的測試結果不是很正確嗎?測試異步異步等待JavaScript函數

以下是我的測試,使用Nock嘲笑服務。

it('Should call async validation function when button is clicked',() => { 
    const request = nock(/.*/) 
     .get('/my-service/logincodes/abc123') 
     .reply(404); 

    const comp = mount(
     <LoginCodeView /> 
    ); 
    expect(comp.instance().doesLoginCodeExist('abc123')).to.equal('Your Login code is not recognized.'); 
}); 

和被測功能:

doesLoginCodeExist = async (loginCode) => { 
    if (loginCode.match(loginPattern)) { 
     const response = await MyService.getUserByLoginCode(loginCode); 

     if (response.code) { 
     return {}; 
     } else if (response.status === 404) { 
     return { error: 'Your login code is not recognized.', success: null }; 
     } 
     return { error: 'Service is temporarily unavailable.', success: null }; 
    } 
    return null; 
    }; 

我已經註銷的代碼採用哪條路線,它確實出現了進入如預期的那樣否則如果分支,但是我總是得到一個空對象{}返回,而不是與預期的錯誤和成功屬性的對象?

+3

一個'async'函數總是返回一個'Promise'對象。我懷疑這就是你所說的空對象。你可以嘗試使你的測試函數'async'並在那裏使用'await'。 –

+0

感謝@AlexanderO'Mara讓我的測試異步等待工作的魅力。 – deanmau5

回答

2

一個async函數總是返回一個Promise對象。我懷疑這就是你所說的空對象。

作爲一種解決方案,您可以嘗試使您的測試功能async和使用await。然後你可以測試承諾解決的價值。

2

使我的測試異步等待解決了這個問題。

it('Should call async validation function when button is clicked', async() => { 
    const request = nock(/.*/) 
     .get('/my-service/logincodes/abc123') 
     .reply(404); 

    const comp = mount(
     <LoginCodeView /> 
    ); 
    const returned = await comp.instance().doesLoginCodeExist('abc123') 
    expect(returned.error).to.equal('Your Login code is not recognized.'); 
});