Javascript Jest-断言异步函数抛出测试失败

Javascript Jest-断言异步函数抛出测试失败,javascript,reactjs,unit-testing,jestjs,Javascript,Reactjs,Unit Testing,Jestjs,得到以下失败的测试用例,我不确定原因: foo.js async function throws() { throw 'error'; } async function foo() { try { await throws(); } catch(e) { console.error(e); throw e; } } const foo = require('./foo'); describe('foo', () => { it('shoul

得到以下失败的测试用例,我不确定原因:

foo.js

async function throws() {
  throw 'error';
}

async function foo() {
  try {
    await throws();
  } catch(e) {
    console.error(e);
    throw e;
  }
}
const foo = require('./foo');

describe('foo', () => {
  it('should log and rethrow', async () => {
    await expect(foo()).rejects.toThrow();
  });
});
test.js

async function throws() {
  throw 'error';
}

async function foo() {
  try {
    await throws();
  } catch(e) {
    console.error(e);
    throw e;
  }
}
const foo = require('./foo');

describe('foo', () => {
  it('should log and rethrow', async () => {
    await expect(foo()).rejects.toThrow();
  });
});
我希望foo抛出,但出于某种原因,它只是解决了问题,测试失败了:

FAILED foo›应该记录并重试-收到的函数没有抛出


可能缺少异步等待抛出行为的一些基本细节。

似乎这是一个已知的错误:

不过,这是可行的:

describe('foo', () => {
  it('should log and rethrow', async () => {
    await expect(foo()).rejects.toEqual('error')
  });
});

我想你需要的是检查被拒绝的错误

const foo=require('./foo');
描述('foo',()=>{
它('should log and rethrow',async()=>{
wait expect(foo()).rejects.toEqual('error');
});
});

当我不想使用
toEqual
toBe
时,我会使用此代码(就像其他正确答案一样)。相反,我使用
toBeTruthy

async foo() {
  throw "String error";
}

describe('foo', () => {
  it('should throw a statement', async () => {
    await expect(foo()).rejects.toBeTruthy();
  });
});

不要等待它。。。只是
expect(foo()).rejects.toThrow()=因为foo所做的就是返回拒绝的承诺…@Bravo这只是隐藏了问题,因为测试没有等待结果。是的,我看到了。。。但是你不希望(等待foo())来代替吗?我感到头晕:p@Bravo是的,这很令人困惑,但这是测试抛出异步函数的方法:)谢谢,不是100%确定它与测试抛出异步函数相同,但我想这是下一个最好的方法。最后使用了
await expect(foo()).rejects.toBeTruthy()您还可以将代码调整为如下内容,并且应该可以工作:
异步函数throws(){throw new Error('Error');}