Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - assert async function throws test fails

Got the following failing test case and i'm not sure why:

foo.js

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

async function foo() {
  try {
    await throws();
  } catch(e) {
    console.error(e);
    throw e;
  }
}

test.js

const foo = require('./foo');

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

I expect foo to throw but for some reason it just resolves and the test fails:

FAILED foo › should log and rethrow - Received function did not throw

Live example

Probably missing some basic detail of async await throw behavior.

like image 826
Daniel Avatar asked Nov 15 '19 09:11

Daniel


2 Answers

I think what you need is to check the rejected error

const foo = require('./foo');
describe('foo', () => {
  it('should log and rethrow', async () => {
    await expect(foo()).rejects.toEqual('error');
  });
});
like image 152
Mohamed Shalabi Avatar answered Sep 29 '22 09:09

Mohamed Shalabi


Seems like it's a known bug: https://github.com/facebook/jest/issues/1700

This works though:

describe('foo', () => {
  it('should log and rethrow', async () => {
    await expect(foo()).rejects.toEqual('error')
  });
});
like image 28
Juviro Avatar answered Sep 29 '22 08:09

Juviro