Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a jest test to fail on any error thrown?

How can I make a jest test fail on any error thrown?

I have tried around a bit, but haven't nailed the syntax yet.

test('getArcId => Error', async () => {
    await expect(client.getArcId('skynet')).rejects.toThrow();
});

I get the error message

getArcId › getArcId => Error

expect(received).rejects.toThrow()

Received function did not throw

However the following test passes, so the function I intend to test does throw (at least to the best of my understanding of what throw means):

test('getArcId => Error', async () => {
    await client.getArcId('skynet').catch(e => 
        expect(e.message).toBe('Command failure')
    );
});
like image 894
user1283776 Avatar asked Dec 04 '22 18:12

user1283776


2 Answers

I couldn't get toThrow() to work, but doing the tests like so did work;

it('throws on connection error', async () => {
    expect.assertions(1);
    await expect(nc.exec({ logger: true }))
    .rejects.toEqual(Error('No command provided to proxy.'));
});

If I reject just a message;

.rejects.toEqual('some message');
like image 129
Carl Avatar answered Jan 03 '23 09:01

Carl


For Jest exception handling to work as expected, pass it an anonymous function like:

test('getArcId => Error', async () => {
    await expect(() => client.getArcId('skynet')).rejects.toThrow();
});

From the jest documentation

test('throws on octopus', () => {
  expect(() => {
    drinkFlavor('octopus');
  }).toThrow();
});

Please note the anonymous function. Yeah, that got me a few times :)

like image 44
Peter Avatar answered Jan 03 '23 09:01

Peter