1

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)
  • Mock return for `this.itemRepository.getById`. And don't async with .map https://stackoverflow.com/questions/33438158/best-way-to-call-an-asynchronous-function-within-map – hoangdv Mar 19 '22 at 03:27
  • Thanks, @hoangdv for your comment, I realized in JS Array functions even I didn't use async the result was the same and I understood these functions maybe have something running under the hood and the way that functions throws the error maybe is different I changed the way that I'm doing the validation and I updated my question – Guilherme Garcia Alves Mar 19 '22 at 17:20

0 Answers0