I have the following validation code at a Service Class:
order.items.map(async (item) => {
const itemResult = await this.itemRepository.getById(item.id)
if(itemResult == undefined && itemResult == null){
throw new NotFoundError('Item not found in database')
}
})
And I created the following test at Jest with an Order that doesn't have an Item on the Database:
it('Should validate a Order', async () => {
const item: Item = {
id: '2',
name: 'Item do not exist',
price: '20.0'
}
const order = {
id: uuidv4(),
amount: '100.0',
items: [item],
created_at: new Date()
} as Order
await expect(async () => {
orderService.createOrder(order)
}).toThrowError()
})
But when I run the Jest the test fails and the terminal is shown:
RUNS src/core/service/OrderService.spec.ts
/home/user/repo/projetc/src/core/service/OrderService.ts:1162
throw new NotFoundError_1.NotFoundError('Item not found in database');
^
NotFoundError: Item not found in database
at OrderService.<anonymous> (/home/user/repo/projetc/src/core/service/OrderService.ts:1162:19)
at Generator.next (<anonymous>)
at fulfilled (/home/user/repo/projetc/src/core/service/OrderService.ts:1058:24)
[Update]
After the hoangdv comment I changed the way that I'm validating for this:
const itemResult = await Promise.all(order.items.map(async (item) => {
return await this.itemRepository.getById(item.id)
}))
itemResult.forEach((item) => {
if(!item){
throw new NotFoundError('Item not found in database')
}
})
And changed the test to add rejects
Jest property:
await expect(async () => {
await orderService.createOrder(order)
}).rejects.toThrow(NotFoundError)