无法从Jest测试获得有关async-await-try-catch函数的响应

时间:2019-04-26 11:25:06

标签: javascript unit-testing ecmascript-6 async-await jestjs

我正在为异步等待功能编写一个简单的笑话测试,该函数使用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

2 个答案:

答案 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)

resolvesrejects都要求您返回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!
});