Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  100] [ 3]  / answers: 1 / hits: 6349  / 3 Years ago, mon, february 1, 2021, 12:00:00

I am writing a test that supposedly should catch an exception


describe('unauthorized', () => {
const client = jayson.Client.http({
host: 'localhost',
port: PORT,
path: '/bots/uuid',
})

it('should return unauthorized response', async () => {
const t = async () => {
await client.request('listUsers', {})
}

expect(t()).toThrow(Error)
})
})

I am pretty sure that client.request is throwing an exception but Jest says:



Received function did not throw



const test = async () => {
...
}

Is the correct way to check?


UPDATE


If I change to


expect(t()).toThrow(Error)

I got


expect(received).toThrow(expected)

Matcher error: received value must be a function

Received has type: object
Received has value: {}

More From » typescript

 Answers
13

You can use rejects


 it('should return unauthorized response', async () => {
await expect(client.request('listUsers', {})).rejects.toThrow(/* error you are expecting*/);
})

Or


You can use try/catch


 it('should return unauthorized response', async () => {
const err= null;
try {
await client.request('listUsers', {});
} catch(error) {
err= error; //--> if async fn fails the line will be executed
}

expect(err).toBe(/* data you are expecting */)
})

You can check the error type of and the error message


[#1851] Thursday, January 28, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marcos

Total Points: 331
Total Questions: 106
Total Answers: 104

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
marcos questions
Thu, Feb 24, 22, 00:00, 2 Years ago
Sat, Apr 17, 21, 00:00, 3 Years ago
Tue, Jan 26, 21, 00:00, 3 Years ago
Wed, Jan 6, 21, 00:00, 3 Years ago
Tue, May 26, 20, 00:00, 4 Years ago
;