我正在为异步等待功能编写一个简单的笑话测试,该函数使用try-catch样式语法;
不幸的是,该函数没有返回响应。我知道我很傻。我可以多留一双眼睛。
PS:大多数Internet资源都集中在简单的async-await上,但很少有很多资源集中在async-await-try-catch上;因此,要求SO。
async justAnotherAsyncAwait () {
try {
console.log(`inside async await`);
return Promise.resolve('HIIII');
} catch (error) {
return Promise.reject(error);
}
}
expect(justAnotherAsyncAwait()).resolves.toEqual('HIIII')
控制台读取inside async-await
答案 0 :(得分:0)
const justAnotherAsyncAwait = async () => {
try {
console.log(`inside async await`);
return await Promise.resolve('HIIII');
} catch (error) {
return Promise.reject(error);
}
}
describe('simple async await test', () => {
it('resolve HIIII', () => {
expect(justAnotherAsyncAwait()).resolves.toEqual('HIIII')
});
});
答案 1 :(得分:0)
resolves
和rejects
都要求您返回Promise
:
test('justAnotherAsyncAwait', () => {
// return the Promise
return expect(justAnotherAsyncAwait()).resolves.toBe('HIIII'); // Success!
});
...或使用async
测试函数并在await
上调用Promise
:
test('justAnotherAsyncAwait', async () => { // <= async test function
// await the Promise
await expect(justAnotherAsyncAwait()).resolves.toBe('HIIII'); // Success!
});
另一个说明:
async
函数总是返回一个Promise
,它返回的Promise
将解析为返回值,或者如果返回Error
则拒绝会抛出Error
,因此通常不需要在try / catch
函数体中使用async
。
这是一个简单的例子:
const func = async (arg) => {
if (arg === 'pass') {
return 'HIIII';
}
throw new Error('something bad happened');
}
test('justAnotherAsyncAwait', async () => {
await expect(func('pass')).resolves.toBe('HIIII'); // Success!
await expect(func()).rejects.toThrow('something bad happened'); // Success!
});