Daniel
Daniel

Reputation: 6481

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.

Upvotes: 6

Views: 3531

Answers (3)

Guillem Puche
Guillem Puche

Reputation: 1404

I use this code when I don't want to use toEqual or toBe (like the other correct answers). Instead, I use toBeTruthy.

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

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

Upvotes: 1

Mohamed Shalabi
Mohamed Shalabi

Reputation: 106

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');
  });
});

Upvotes: 9

Juviro
Juviro

Reputation: 190

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')
  });
});

Upvotes: 2

Related Questions