2017-10-15 113 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.'); 
});